Find a spanning tree to minimize the difference between the maximum edge and the minimum edge. Because the data is too small, the lower bound of the brute force enumeration is obtained. Take Min as the final result.
1 #include<cstdio> 2 #include<algorithm> 3 #include<cstring> 4 using namespace std; 5 int n,m,fa[101],rank[101]; 6 void clear(){for(int i=1;i<=n;i++) fa[i]=i; memset(rank,0,sizeof(rank));} 7 int findroot(int x) 8 { 9 if(fa[x]==x) return x;10 int rt=findroot(fa[x]);11 fa[x]=rt;12 return rt;13 }14 void Union(int U,int V)15 {16 if(rank[U]<rank[V]) fa[U]=V;17 else18 {19 fa[V]=U;20 if(rank[U]==rank[V]) rank[U]++;21 }22 }23 struct Edge{int u,v,w;};24 bool cmp(const Edge &a,const Edge &b){return a.w<b.w;}25 Edge edges[5001];26 int tot,ans,maxv;27 int main()28 {29 while(1)30 {31 scanf("%d%d",&n,&m);32 if(!n) break;33 for(int i=1;i<=m;i++) scanf("%d%d%d",&edges[i].u,&edges[i].v,&edges[i].w);34 sort(edges+1,edges+m+1,cmp); ans=2147483647;35 for(int j=1;j<=m;j++)36 {37 tot=0; clear();38 for(int i=j;i<=m;i++)39 {40 int f1=findroot(edges[i].u),f2=findroot(edges[i].v);41 if(f1!=f2) {Union(f1,f2); tot++; if(tot==n-1) {maxv=edges[i].w; goto WIN;}}42 }43 continue;44 WIN:ans=min(ans,maxv-edges[j].w);45 }46 printf("%d\n",ans!=2147483647 ? ans : -1);47 }48 return 0;49 }
[Kruscal] [Minimum Spanning Tree] poj3522 slim Span