Http://poj.org/problem? Id = 3522
Ask for the minimum spanning tree with the smallest difference between the longest side and the shortest side, and output the difference value if-1 is not possible.
Problem: the Kruskal algorithm is used to sort edges in ascending order and then select the edges to construct the Minimum Spanning Tree. Therefore, after using Kruskal and sorting, select the first edge as the starting edge to construct it, this edge is discarded after being constructed. Compare the difference between the maximum edge and the minimum edge of each spanning tree.
1 # include <iostream> 2 # include <cstring> 3 # include <cstdio> 4 # include <cstdlib> 5 # include <cmath> 6 # include <string> 7 # include <vector> 8 # include <list> 9 # include <map> 10 # include <queue> 11 # include <stack> 12 # include <bitset> 13 # include <algorithm> 14 # include <numeric> 15 # include <functional> 16 # include <set> 17 # include <fstream> 18 19 using namespace STD; 20 21 const int INF = 0xff Fffff; 22 23 const int maxv = 110; 24 const int MaxE = 110*110; 25 26 int par [maxv], rankh [maxv]; 27 struct edge {28 int U, v, cost; 29}; 30 edge es [MaxE]; 31 int V, E; 32 int n, m; 33 int DIF; 34 35 void Init (int n) 36 {37 for (INT I = 0; I <= N; I ++) 38 {39 par [I] = I; 40 rankh [I] = 0; 41} 42} 43 44 int find (int x) 45 {46 If (par [x] = x) return X; 47 else return par [x] = find (par [x]); 48} 49 50 void unite (int x, Int y) 51 {52 X = find (x); 53 y = find (y); 54 if (x = y) return; 55 if (rankh [x] <rankh [y]) {56 par [x] = y; 57 rankh [y] + = rankh [x]; 58} else {59 par [y] = x; 60 rankh [x] + = rankh [y]; 61} 62} 63 64 bool same (int x, int y) 65 {66 return find (x) = find (y); 67} 68 69 bool CMP (const edge & E1, const edge & E2) 70 {71 return e1.cost <e2.cost; 72} 73 74 void Kruskal () 75 {76 DIF = inf; 77 sort (ES, es + e, CMP); 78 for (int I = 0; I <E; I ++) 79 {80 Init (V); 81 int CNT = 0, TMP = inf; 82 For (Int J = I; j <E; j ++) 83 {84 edge e = es [J]; 85 if (! Same (E. u, E. v) {86 unite (E. u, E. v); 87 CNT ++; 88 If (CNT = V-1) {89 TMP = es [J]. cost-es [I]. cost; 90 break; 91} 92} 93} 94 DIF = min (DIF, TMP); 95} 96} 97 int main () 98 {99 // freopen ("/users/Apple/desktop/summer/poj 3522/poj 3522/in", "r", stdin ); 100 while (scanf ("% d", & N, & M )! = EOF) 101 {102 If (n + M = 0) break; 103 V = N; 104 E = m; 105 for (INT I = 0; I <m; I ++) 106 {107 scanf ("% d", & ES [I]. u, & ES [I]. v, & ES [I]. cost); 108} 109 Kruskal (); 110 if (DIF = inf) puts ("-1"); 111 else printf ("% d \ n", DIF ); 112} 113 return 0; 114}
Poj 3522 slim Span