码迷,mamicode.com
首页 > 其他好文 > 详细

POJ1251 Jungle Roads

时间:2015-10-26 12:00:52      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

解题思路:看懂题意是关键,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

 

POJ1251 Jungle Roads

标签:

原文地址:http://www.cnblogs.com/loveprincess/p/4910591.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!