题意:
求最大边与最小边差值最小的生成树,若不存在生成树则输出-1。
思路:
用Kruskal算法枚举最小边即可
1 #include <cstdio> 2 #include <algorithm> 3 using namespace std; 4 const int N = 110, M = 5000; 5 struct SIDE 6 { 7 int from; 8 int to; 9 int distance; 10 }edge[M]; 11 int cnt[N]; 12 bool cmp(const SIDE a, const SIDE b){ 13 return a.distance < b.distance; 14 } 15 int Find(int x){ 16 return cnt[x] == x ? x : Find(cnt[x]); 17 } 18 int main(void) 19 { 20 int n, m, a, b, MIN, ok; 21 while(scanf("%d %d", &n, &m), n+m) 22 { 23 for(int i=0; i<m; ++i) 24 scanf("%d %d %d", &edge[i].from, &edge[i].to, &edge[i].distance); 25 sort(edge, edge+m, cmp); 26 MIN = 0x3f3f3f3f; 27 ok = 0; 28 for(int start=0; start<=m-n+1; ++start) 29 { 30 for(int i=1; i<=n; ++i) 31 cnt[i] = i; 32 int i, j = 0; 33 for(i=start; i<m && j<n-1; ++i) 34 { 35 a = Find(edge[i].from); 36 b = Find(edge[i].to); 37 if(a != b) 38 cnt[b] = a, ++j; 39 } 40 if(j == n-1) 41 MIN = min(MIN, edge[i-1].distance - edge[start].distance), ok = 1; 42 } 43 printf("%d ", ok ? MIN : -1); 44 } 45 }