UVA1395 (最苗条的最小生成树)
链接
https://vjudge.net/problem/UVA-1395
代码
#include<bits/stdc++.h> using namespace std; #define ull unsigned long long #define ll long long const int maxn=5e4+10; int par[maxn]; int rank1[maxn]; void init(int n) //初始化 { for(int i=0;i<=n;i++) { par[i]=i; rank1[i]=0; } } int find(int x) { if(par[x]==x) { return x; } else { return par[x]=find(par[x]); } } void unite(int x,int y) { x=find(x); y=find(y); if(x==y) return ; if(rank1[x]<rank1[y]) { par[x]=y; } else { par[y]=x; } if(rank1[x]==rank1[y]) rank1[x]++; } int n,m; struct edge{ int x,y,cost; }e[50005]; bool cmp(const edge e1,const edge e2) { return e1.cost<e2.cost; } int main() { while(cin>>n>>m&&(n||m)) { for(int i=1;i<=m;i++) { cin>>e[i].x>>e[i].y>>e[i].cost; } int res=-1; sort(e+1,e+m+1,cmp); for(int i=1;i<=m;i++) { init(n); int num=0; for(int j=i;j<=m;j++) { edge e1=e[j]; int x=find(e1.x); int y=find(e1.y); if(x!=y) { num++; unite(e1.x,e1.y); if(num==n-1) { if(res==-1) res=e[j].cost-e[i].cost; else res=min(res,e[j].cost-e[i].cost); } } // cout<<i<<" "<<num<<"\n"; } } cout<<res<<"\n"; } return 0; }