uva3887Slim Span

题目链接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1888

求最大边权与最小边权差值最小的生成树的权值。

 1 #include<cstdio>
 2 #include<algorithm>
 3 
 4 using namespace std;
 5 struct node
 6 {
 7     int u,v,w;
 8     bool operator <(const node &a) const {
 9     return w<a.w;
10     }
11 }e[10010];
12 
13    int n,m;
14    int f[110];
15    int cha=1000000,cnt;
16 void unit()
17 {
18     for(int i=0;i<=n;i++) f[i]=i;
19 }
20 int  gf(int x)
21 {
22     return x==f[x]?x:f[x]=gf(f[x]);
23 }
24 void uni(int x,int y)
25 {
26     int px=gf(x);
27     int py=gf(y);
28     f[px]=py;
29 }
30 void kru()
31 {
32    for(int j=0;j+n-2<m;j++)
33     {
34         unit();
35         cnt=0;
36         for(int i=j;i<m;i++)
37         {
38             if(gf(e[i].u)!=gf(e[i].v)) 
39             {
40                  uni(e[i].u,e[i].v);
41                  cnt++;
42              }
43              if(cnt==n-1)
44              {
45                      cha=min(cha,e[i].w-e[j].w);
46                     break;
47               }
48 
49            }
50         }
51 }
52 int main()
53 {
54 
55 
56     while(scanf("%d%d",&n,&m)&&(n||m))
57     {
58         cha=1000000;
59         for(int i=0;i<m;i++){
60             scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);
61         }
62         sort(e,e+m);
63         kru();
64        if(cha!=1000000) printf("%d
",cha);
65        else puts("-1");
66     }
67     return 0;
68 }   
原文地址:https://www.cnblogs.com/yijiull/p/6616430.html