pku 2377 Bad Cowtractors 最大生成树

直接贴代码了,没什么好说的
 1 import java.io.*;
 2 import java.util.Arrays;
 3 class node implements Comparable
 4 {
 5     int a,b,c;
 6     public int compareTo(Object pos)
 7     {
 8         return ((node)pos).c-c;
 9     }
10 };
11 public class Main {
12     static int pre[];
13     static int find(int pos)
14     {
15         if(pre[pos]==pos)
16             return pos;
17         else
18         {
19             pre[pos]=find(pre[pos]);
20             return pre[pos];
21         }
22     }
23     public static void main(String[] args) throws IOException{
24         StreamTokenizer in=new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
25         int n,m;
26         in.nextToken();
27         n=(int)in.nval;
28         in.nextToken();
29         m=(int)in.nval;
30         node []data=new node[m];
31         pre=new int[n+1];
32         for(int i=1;i<=n;i++)
33             pre[i]=i;
34         for(int i=0;i<m;i++)
35         {
36             data[i]=new node();
37             in.nextToken();
38             data[i].a=(int)in.nval;
39             in.nextToken();
40             data[i].b=(int)in.nval;
41             in.nextToken();
42             data[i].c=(int)in.nval;
43         }
44         Arrays.sort(data);
45         int count=0,total=0;
46         for(int i=0;i<m&&count<n-1;i++)
47         {
48             if(find(data[i].a)!=find(data[i].b))
49             {
50                 pre[find(data[i].a)]=find(data[i].b);
51                 total+=data[i].c;
52                 count++;
53             }
54         }
55         if(count<n-1)
56             System.out.println(-1);
57         else
58             System.out.println(total);
59 
60     }
61 
62 }
63 


posted on 2010-11-07 02:34 yzhw 阅读(229) 评论(0)  编辑 收藏 引用 所属分类: graph


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2010年10月>
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

导航

统计

公告

统计系统

留言簿(1)

随笔分类(227)

文章分类(2)

OJ

最新随笔

搜索

积分与排名

最新评论

阅读排行榜