POJ1251 Jungle Roads

解题思路:看懂题意是关键,Kruskal算法,最小生成树模板。

上代码:

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 using namespace std;
 5 const int maxn = 80; //边的最大值
 6 int A[30], n, k, vis[maxn], father[30];
 7 
 8 int Find(int x)
 9 {
10     return father[x] == x ?  x : father[x] = Find(father[x]);
11 }
12 
13 struct node{
14     int x, y, w;
15 }p[maxn];
16 
17 int cmp(node A, node B)
18 {
19     return A.w < B.w;//从小到大
20 }
21 
22 int main()
23 {
24     char ch;
25     int x, b;
26     while(~scanf("%d", &n) && n)
27     {
28         int t = n - 1;
29         int cnt = 0;
30         //要初始化哦
31         for(int i = 1; i <= n; i++) father[i] = i;
32         while(t--)
33         {
34             scanf(" %c", &ch);
35             int m = ch - 'A' + 1;
36             scanf("%d", &k);
37             while(k --)
38             {
39                 p[cnt].x = m;//放在循环里面
40                 scanf(" %c %d", &ch, &x);
41                 b = ch - 'A' + 1;
42                 p[cnt].y = b, p[cnt++].w = x;
43             }
44         }
45         int sum = 0;
46         sort(p, p + cnt, cmp);
47         for(int i = 0; i < cnt; i++)
48         {
49             int rootx = Find(p[i].x);
50             int rooty = Find(p[i].y);
51             //根节点不同,则加起来,并放到同一个集合
52             if(rootx != rooty)
53             {
54                 sum += p[i].w;
55                 father[rootx] = rooty;
56             }
57         }
58         printf("%d\n", sum);
59     }
60     return 0;
61 }
View Code

 

posted on 2015-10-26 11:01  改写历史,倾尽天下  阅读(125)  评论(0编辑  收藏  举报

导航