POJ 3522 Slim Span 最小生成树,暴力 难度:0

kruskal思想,排序后暴力枚举从任意边开始能够组成的最小生成树

#include <cstdio>
#include <algorithm>
using namespace std; const int maxn = 101;
const int maxe = maxn * maxn / 2;
struct edge{
int f,t,c;
bool operator <(edge e2)const {
return c<e2.c;
}
}e[maxe]; int par[maxn],num[maxn],n,m; void init(){
for(int i = 1;i <= n;i++){
par[i] = i;
num[i] = 1;
}
} int fnd(int a){
return par[a] == a? a: par[a] = fnd(par[a]);
} bool same(int a,int b){
return fnd(a) == fnd(b);
} void unit(int a,int b){
if(!same(a,b)){
num[fnd(a)] += num[fnd(b)];
num[fnd(b)] = 0;
par[fnd(b)] = fnd(a);
}
} int main(){
while(scanf("%d%d",&n,&m) == 2 && n){
for(int i = 0; i < m ; i++){
scanf("%d%d%d",&e[i].f,&e[i].t,&e[i].c);
}
sort(e,e+m);
int ans = 0x7fffffff;
for (int i = 0;i <= m - n + 1;i++){
init();
int ret = 0;
for(int j = i; num[fnd(1)] < n && j < m; j++){
unit(e[j].f,e[j].t);
ret = max(ret,e[j].c - e[i].c);
}
if(num[fnd(1)] == n)ans = min(ans,ret);
}
if(ans == 0x7fffffff){puts("-1");}
else printf("%d\n",ans);
}
return 0;
}
上一篇:Java类的加载の动态


下一篇:UVA 1395 Slim Span 最小生成树