[Kruscal] [Minimum Spanning Tree] poj3522 slim Span

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.