uva 1395 Slim Span

题目: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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值