POJ3522 (Kruskal+生成树最小苗条度)

题目链接:

http://poj.org/problem?id=3522

题意:求生成树里最大边权与最小边权的差值的最小值(最小苗条度)。

解题思路:先把边排序,从小到大枚举生成树,这样的话差值肯定就是最小的,然后从所有可生成的差值里选最小的。

代码如下:

#include<cstdio>
#include<algorithm>
#include<cstring>
#define MAX_N 111
using namespace std;
int N, M;
int father[MAX_N];
bool flag, ok;
struct edge {
	int from, to;
	int cost;
}E[MAX_N*MAX_N];

bool cmp(edge a, edge b)
{
	return a.cost < b.cost;
}
void init()
{
	for (int i = 1;i <= N;i++)
		father[i] = i;
}

int  Find(int x)
{
	if (father[x] == x)
		return x;
	return father[x] = Find(father[x]);
}

bool Same(int x, int y)
{
	return Find(x) == Find(y);
}

void UnionSet(int x,int y)
{
	int u = Find(x), v = Find(y);
	if (u == v)
		return;
	father[u] = v;
}

int Kruskal(int u)
{
	init();
	int tot = 0;
	int MAX_cost = -1;
	int MIN_cost = 10010;
	for (int i = u;i <= M;i++)
	{
		if (!Same(E[i].from, E[i].to))
		{
			MAX_cost = max(MAX_cost, E[i].cost);
			MIN_cost = min(MIN_cost, E[i].cost);
			UnionSet(E[i].from, E[i].to);
			tot++;
		}
		if (tot == N - 1)
		{
			flag = true;
			ok = true;
			break;
		}
	}
	return MAX_cost - MIN_cost;
}
int main()
{
	while (scanf("%d%d", &N, &M) == 2)
	{
		ok = false;//是否存在连通的生成树
		int Min = 10010;
		if (N == 0 && M == 0) break;
		for (int i = 1;i <= M;i++)
			scanf("%d%d%d", &E[i].from, &E[i].to, &E[i].cost);
		sort(E + 1, E + 1 + M, cmp);
		for (int i = 1;i <= M;i++)
		{
			flag = false;
			int tmp = Kruskal(i);
			if (flag)//当前枚举生成树联通
				Min = min(Min, tmp);
		}
		if (!ok)
			printf("-1\n");
		else
		printf("%d\n", Min);
	}
	return 0;
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值