Slim Span UVA - 1395
題解:按權值排序後遍歷L-R的點看是否滿足生成樹的條件,滿足去找L+1-R,不滿足去找L-R+1。如果1-m不滿足那麼就應該輸出-1。
AC代碼:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 105;
#define _for(i,a,b) for(int i=a;i<=b;i++)
struct node
{
int x,y,value;
bool operator< (const node& a)const
{
return value<a.value;
}
}a[maxn*maxn];
int n,m,ans,fa[maxn];
int find(int x)
{
return x==fa[x]?x:fa[x]=find(fa[x]);
}
bool check(int x,int y)
{
int k = n;
_for(i,x,y)
{
int p = find(a[i].x);
int q = find(a[i].y);
if(p==q)continue;
fa[p]=q;
k--;
}
if(k==1)return true;
else return false;
}
int main(int argc, char const *argv[])
{
//freopen("now.in","r",stdin);
while(scanf("%d%d",&n,&m))
{
if(n==0&&m==0)break;
_for(i,1,m)cin>>a[i].x>>a[i].y>>a[i].value;
sort(a+1,a+1+m);
ans = a[m].value-a[1].value;
_for(i,1,m)
{
_for(j,i+1,m)
{
_for(i,1,n)fa[i]=i;
if(check(i,j))
{
ans=min(ans,a[j].value-a[i].value);
break;
}
}
}
_for(i,1,n)fa[i]=i;
if(!check(1,m))ans=-1;
printf("%d\n",ans);
}
return 0;
}