POJ 3522

来源:互联网 发布:阿里企业邮箱端口 编辑:程序博客网 时间:2024/06/05 18:02
#include<cstdio>#include<algorithm>#include<vector>using namespace std;const int maxn=1005;struct Edge{int from,to,w;Edge(int from,int to,int w):from(from),to(to),w(w){}bool operator < (const Edge s)const{return w<s.w;}};struct krusckal{int n,ans;int father[maxn];vector<int>path;vector<Edge> edge;int getfather(int x){return x==father[x]?x:father[x]=getfather(father[x]);}void init(int n){this->n=n;path.clear();edge.clear();}void add_edge(int from,int to,int w){edge.push_back(Edge(from,to,w));}bool solve(int front){int x,y,k=front,cnt=0;path.clear();ans=2e9;for(int i=1;i<=n;i++)father[i]=i;while(cnt<n-1&&k<edge.size()){x=getfather(edge[k].from);y=getfather(edge[k].to);if(x!=y){father[x]=y;cnt++;path.push_back(k);}k++;}if(cnt<n-1)return false;ans=edge[path[cnt-1]].w-edge[front].w;return true;}};int main(){int n,i,j,x,m,y,w,ans;while(true){scanf("%d%d",&n,&m);if(!n&&!m)return 0;krusckal solver;solver.init(n);ans=2e9;for(i=1;i<=m;i++){scanf("%d%d%d",&x,&y,&w);solver.add_edge(x,y,w);}sort(solver.edge.begin(),solver.edge.end());for(i=0;i<=m-n+1;i++){if(solver.solve(i))ans=min(ans,solver.ans);}printf("%d\n",ans==2e9?-1:ans);}}


0 0
原创粉丝点击