POJ1287 Networking
解题思路:Kruskal模板题,重复输入的情况,本题是无向图。
见代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 }