码迷,mamicode.com
首页 > Web开发 > 详细

POJ1287 Networking

时间:2015-10-26 13:28:09      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

解题思路:Kruskal模板题,重复输入的情况,本题是无向图。

见代码:

技术分享
 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<cstring>
 4 using namespace std;
 5 #define inf 0x3f3f3f3f
 6 const int maxn = 100005;
 7 int n, m, father[55],w[55][55];
 8 
 9 int Find(int x)
10 {
11     return father[x] == x ? x : father[x] = Find(father[x]);
12 }
13 
14 struct node{
15     int x, y, w;
16 }p[maxn];
17 
18 int cmp(node A, node B)
19 {
20     return A.w < B.w;
21 }
22 
23 int main()
24 {
25     int a, b, x;
26     while(~scanf("%d", &n) && n)
27     {
28         scanf("%d", &m);
29         for(int i = 1; i <= n; i++)
30         {
31             for(int j = i; j <= n; j++)
32             {
33                 if(i == j) w[i][j] = 0;
34                 else w[i][j] = w[j][i] = inf;
35             }
36         }
37         for(int i = 0; i < m; i++)
38         {
39             scanf("%d%d%d", &a, &b, &x);
40             p[i].x = a, p[i].y = b, p[i].w = x;
41             //如果两点有多条路,这步取更小的值
42             if(w[a][b] > x) w[a][b] = w[b][a] = x;
43         }
44         sort(p, p + m, cmp); //从小到大
45         //并查集初始化
46         for(int i = 1; i <= n; i++) father[i] = i;
47         int sum = 0;
48         for(int i = 0; i < m; i++)
49         {
50             int rootx = Find(p[i].x);
51             int rooty = Find(p[i].y);
52             //不在同一个集合就加起来
53             if(rootx != rooty)
54             {
55                 sum += p[i].w;
56                 father[rootx] = rooty;
57             }
58         }
59         printf("%d\n", sum);
60 
61     }
62     return 0;
63 }
View Code

 

POJ1287 Networking

标签:

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

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