题意:这道题重新定义了最小生成树的含义是生成树中最小的边和最大的边的差值。然后给你一个无向带权图,让你输出最小生成树的值。若没有输出-1。
思路:很简单稍微想一下就可以知道,我们只要枚举生成树中最小的那条边然后在这个基础上求最小生成树,这样每次更新最小值,最终就能得到答案。
代码如下:
1 /************************************************** 2 * Author : xiaohao Z 3 * Blog : http://www.cnblogs.com/shu-xiaohao/ 4 * Last modified : 2014-02-08 18:56 5 * Filename : uva_1395.cpp 6 * Description : 7 * ************************************************/ 8 9 #include <iostream> 10 #include <cstdio> 11 #include <cstring> 12 #include <cstdlib> 13 #include <cmath> 14 #include <algorithm> 15 #include <queue> 16 #include <stack> 17 #include <vector> 18 #include <set> 19 #include <map> 20 #define MP(a, b) make_pair(a, b) 21 #define PB(a) push_back(a) 22 23 using namespace std; 24 typedef long long ll; 25 typedef pair<int, int> pii; 26 typedef pair<unsigned int,unsigned int> puu; 27 typedef pair<int, double> pid; 28 typedef pair<ll, int> pli; 29 typedef pair<int, ll> pil; 30 31 const int INF = 0x3f3f3f3f; 32 const double eps = 1E-6; 33 const int LEN = 102; 34 struct E{ 35 int u, v, val; 36 }; 37 E edge[LEN*LEN], te[LEN*LEN]; 38 int n, m, tag, parent[LEN]; 39 40 bool cmp(E a, E b){return a.val < b.val;} 41 //UFSet 42 void init(){for(int i=0; i<LEN; i++) parent[i] = i;} 43 int Find(int x){return parent[x] == x ? x:parent[x] = Find(parent[x]);} 44 45 int kruskal(){ 46 int cnt = 0, ret = 0; 47 for(int i=0; i<m; i++){ 48 if(edge[i].val < tag) continue; 49 int pa = Find(edge[i].u), pb = Find(edge[i].v); 50 if(pa == pb) continue; 51 parent[pa] = pb; 52 cnt ++; 53 ret = max(ret, edge[i].val - tag); 54 if(cnt == n-1) break; 55 } 56 if(cnt == n-1)return ret; 57 else return INF; 58 } 59 60 int main() 61 { 62 // freopen("in.txt", "r", stdin); 63 64 while(scanf("%d%d", &n, &m)!=EOF){ 65 if(!n && !m) break; 66 for(int i=0; i<m; i++){ 67 scanf("%d%d%d", &edge[i].u, &edge[i].v, &edge[i].val); 68 te[i].u = edge[i].u, te[i].v = edge[i].v, te[i].val = edge[i].val; 69 } 70 int ans = INF; 71 sort(edge, edge+m, cmp); 72 for(int i=0; i<m; i++){ 73 tag = te[i].val; 74 init(); 75 ans = min(ans, kruskal()); 76 } 77 if(ans != INF)printf("%d ", ans); 78 else printf("-1 "); 79 } 80 return 0; 81 }