首页 > 代码库 > 【poj3522】 Slim Span

【poj3522】 Slim Span

http://poj.org/problem?id=3522 (题目链接)

题意

  求最小生成树的最大边与最小边差最小。

Solution

  排序后滑动窗口维护

代码

// poj3522#include<algorithm>#include<iostream>#include<cstdlib>#include<cstring>#include<cstdio>#include<cmath>#define LL long long#define inf 2147483640#define Pi acos(-1.0)#define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout);using namespace std;const int maxn=5010;struct edge {int u,v,w;}e[maxn];int n,m,fa[maxn];bool cmp(edge a,edge b) {	return a.w<b.w;}int find(int x) {	return fa[x]==x ? x : fa[x]=find(fa[x]);}int main() {	while (scanf("%d%d",&n,&m)!=EOF && (n || m)) {		for (int i=1;i<=m;i++) scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w);		sort(e+1,e+1+m,cmp);		int ans=inf;		for (int l=1;l<=m;l++) {			int cnt=0,flag=0;			for (int i=1;i<=n;i++) fa[i]=i;			for (int i=l;i<=m;i++) {				int r1=find(e[i].u),r2=find(e[i].v);				if (r1!=r2) cnt++,fa[r1]=r2;				if (cnt==n-1) {flag=1;ans=min(ans,e[i].w-e[l].w);break;}			}			if (!flag) break;		}		if (ans==inf) printf("-1\n");		else printf("%d\n",ans);	}	return 0;}

  

【poj3522】 Slim Span