村村通工程 最小生成树+并查集

问题 D: 村村通工程
时间限制: 1 Sec 内存限制: 128 MB

题目描述
某国有N个村子,M条道路,为了实现“村村通工程”,现在要”油漆”N-1条道路(因为某些人总是说该国所有的项目全是从国外进口来的,只是漆上本国的油漆罢了),因为“和谐”是此国最大的目标和追求,以致于对于最小造价什么的都不在乎了,只希望你所选出来的最长边与最短边的差越小越好。
输入
第一行给出一个数字TOT,代表有多少组数据,Tot<=6
对于每组数据,首先给出N,M
下面M行,每行三个数a,b,c代表a村与b的村道路距离为c.

输出
输出最小差值,如果无解输出”-1”.
样例输入 Copy
1
4 5
1 2 3
1 3 5
1 4 6
2 4 6
3 4 7
样例输出 Copy
1
提示
【样例说明】
选择1-4,2-4,3-4这三条边.
【数据规模】
1:2 ≤ n ≤ 100 and 0 ≤ m ≤ n(n − 1)/2
2:每条边的权值小于等于10000
3:保证没有自环,没有重边

题目中不是求最小造价,所以不能直接用最小生成树做,可以先从小到大排序,让后依次枚举每个点,看这个点以及其后面的点构成的最小生成树,让后每次取最大边与起点的差的最小值即可,这样的答案一定是最小的,因为最小生成树保证了能联通且选的边尽可能小,也就是每次选取的最大边尽可能小。

#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cmath>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#define X first
#define Y second
using namespace std;

typedef long long LL;
typedef pair<int,int> PII;

const int N=110,M=100010,mod=1e9+7,INF=0x3f3f3f3f;
const double eps=1e-6;

int n,m,t,ans=INF;
int p[N]; 

struct Edge
{
	int a,b;
	int w;
	bool operator < (const Edge &W)const
	{
		return w<W.w;
	}
}edge[M];

int find(int x)
{
	if(x!=p[x]) p[x]=find(p[x]);
	return p[x];
}

int main()
{
//	ios::sync_with_stdio(false);
//	cin.tie(0);

	scanf("%d",&t);
	
	while(t--)
	{
		scanf("%d%d",&n,&m);
		
		ans=INF;
		
		for(int i=1;i<=m;i++)
		{
			int a,b,w;
			scanf("%d%d%d",&a,&b,&w);
			edge[i]={a,b,w};
		}
		
		sort(edge+1,edge+1+m);
		
		for(int q=1;q<=m;q++)
		{
			for(int i=1;i<=n;i++)
			p[i]=i;

			int cnt=0;
			
			for(int i=q;i<=m;i++)
			{
				int a=edge[i].a,b=edge[i].b,w=edge[i].w;
				int pa=find(a),pb=find(b);
				
				if(pa!=pb)
				{
					p[pa]=pb;
					cnt++;
					if(cnt==n-1)
					{
						ans=min(ans,w-edge[q].w);
						break;
					}
				}
			}
		}
		
		if(ans==INF) puts("-1");
		else printf("%d\n",ans);
	}






	return 0;
}










发布了43 篇原创文章 · 获赞 1 · 访问量 1575

猜你喜欢

转载自blog.csdn.net/DaNIelLAk/article/details/105089773
今日推荐