码迷,mamicode.com
首页 > 其他好文 > 详细

UVa1395图论之最小生成树

时间:2015-01-04 17:17:35      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:acm   图论   

//除了套模版之外还有新的思想在其中:枚举。

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <math.h>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <cstring>
#include <sstream>
#include <queue>
#include <stack>
using namespace std;

#define input freopen("input.txt","r",stdin)
#define output freopen("output.txt","w",stdout)
#define For1(i,a,b) for (i=a;i<b;i++)
#define For2(i,a,b) for (i=a;i<=b;i++)
#define Dec(i,a,b) for (i=a;i>b;i--)
#define Dec2(i,a,b) for (i=a;i>=b;i--)
#define Sca_d(x) scanf("%d",&x)
#define Sca_s(x) scanf("%s",x)
#define Sca_c(x) scanf("%c",&x)
#define Sca_f(x) scanf("%f",&x)
#define Sca_lf(x) scanf("%lf",&x)
#define Sca_lu(x) scanf("%I64d",&u)
#define Sca_ld(x) scanf("%I64d",&x)
#define Fill(x,a) memset(x,a,sizeof(x))
#define inf 99999999

const int maxn=200;
const int maxm=20000;
int n,m;
int p[maxn];

struct Edge
{
	int u,v,w;
}edge[maxm];

int find(int x) {return p[x]==x?x:p[x]=find(p[x]);}

int cmp(const void *a,const void *b)
{
	Edge *c=(Edge *)a;
	Edge *d=(Edge *)b;
	if (c->w!=d->w) return c->w - d->w;
}

int main()
{
	//input;
	int i,j,k,l,r,x,y,check,ans;
	while(cin>>n>>m,m+n)
	{
		Fill(edge,0);
		For2(i,1,m)
			cin>>edge[i].u>>edge[i].v>>edge[i].w;
		ans=inf;
		qsort(edge+1,m,sizeof(edge[0]),cmp);
		For2(l,1,m)//l控制当前最小边 
		{
			int maxedge=0;
			int minedge=inf;
			For2(i,0,n) p[i]=i;
			r=l;
			check=0;
			while((check<n-1)&&(r<=m))
			{
				int &u=edge[r].u;
				int &v=edge[r].v;
				x=find(u);
				y=find(v);
				if (x!=y)
				{
					p[x]=y;
					check++;
					maxedge=max(maxedge,edge[r].w);
					minedge=min(minedge,edge[r].w);
				}
				r++;
			}
			if (check==n-1) ans=min(ans,maxedge-minedge);
		}
		if (ans==inf) puts("-1");
		else cout<<ans<<endl;
	}
	return 0;
}



UVa1395图论之最小生成树

标签:acm   图论   

原文地址:http://blog.csdn.net/kevin66654/article/details/42393379

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!