标签:
题意: 求最小生成树中,最大的边减去最小的边 最小值。
看了题解发现真简单=_=
将每条边进行从小到大排序,然后从最小到大一次枚举最小生成树,当构成生成树的时候,更新最小值
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 using namespace std; 6 const int INF = 0x3f3f3f3f; 7 const int Max = 5000; 8 const int N = 110; 9 int father[N]; 10 struct Edge 11 { 12 int x, y, dist; 13 }; 14 Edge edge[Max]; 15 int cmp(Edge t1, Edge t2) 16 { 17 return t1.dist < t2.dist; 18 } 19 int find_father(int x) 20 { 21 if (x == father[x]) 22 return x; 23 return father[x] = find_father(father[x]); 24 } 25 int main() 26 { 27 int n, m; 28 while (scanf("%d%d", &n, &m) != EOF) 29 { 30 if (m == 0 && n == 0) 31 break; 32 for (int i = 0; i < m; i++) 33 { 34 scanf("%d%d%d", &edge[i].x, &edge[i].y, &edge[i].dist); 35 } 36 sort(edge, edge + m, cmp); 37 int minn = INF; 38 for (int i = 0; i < m; i++) 39 { 40 for (int j = 0; j <= n; j++) 41 father[j] = j; 42 int cnt = 0; 43 for (int j = i; j < m; j++) // 依次枚举每一个生成树 44 { 45 int fx = find_father(edge[j].x); 46 int fy = find_father(edge[j].y); 47 if (fx != fy) 48 { 49 father[fx] = fy; 50 cnt++; 51 if (cnt == n - 1) // 一旦构成生成树,j是最大边权,i是最小权,相减更新 52 { 53 minn = min(minn, edge[j].dist - edge[i].dist); 54 break; 55 } 56 } 57 } 58 } 59 if (minn == INF) 60 printf("-1\n"); 61 else 62 printf("%d\n", minn); 63 } 64 return 0; 65 }
标签:
原文地址:http://www.cnblogs.com/zhaopAC/p/5392254.html