当前位置: 代码迷 >> 综合 >> uva 1395 Slim Span
  详细解决方案

uva 1395 Slim Span

热度:38   发布时间:2023-12-06 08:42:47.0

题目:Slim Span


代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<map>
#include<algorithm>
#include<sstream>
#include<queue>
#include<set>
using namespace std;struct Edge {int x,y,z;Edge() {}Edge(int one,int two,int three) {x=one,y=two,z=three;}bool operator <(const Edge& other) const {if(z<other.z||(z==other.z&&x<other.x)||(z==other.z&&x==other.x&&y<other.y)) return true;return false;}
};int n,m;
Edge a[5000];
int fa[105]= {0};
int ans;int find(int x) {if(fa[x]==-1) return x;return fa[x]=find(fa[x]);
}void make() {ans=(1<<30);for(int i=1; i<=m; i++) {memset(fa,-1,sizeof(fa));int s1=(1<<30),s2=0;int cnt=0;for(int j=i; j<=m; j++) {int f1=find(a[j].x),f2=find(a[j].y);if(f1==f2) continue;s1=min(a[j].z,s1),s2=max(a[j].z,s2);fa[f1]=f2;cnt++;if(cnt==n-1) {ans=min(ans,s2-s1);break;}}}
}void readin() {for(int i=1; i<=m; i++) {scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].z);}sort(a+1,a+m+1);
}int main() {while(~scanf("%d%d",&n,&m)&&(n!=0||m!=0)) {readin();make();if(ans==(1<<30)) printf("-1\n");else printf("%d\n",ans);}return 0;
}


  相关解决方案