hdu1863 畅通工程

题目链接
本题和还是畅通工程思路非常类似。
区别在于后者给的图的边数为n*(n-1)/2,是一个无向完全图,一定能找到一个最小生成树。而前者给的边数不定,所以不一定能生成一个最小生成树,需要判断。
所用知识点:kruskal算法(最小生成树) 并查集
代码如下:

#include <iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
struct edge {
	int a, b;
	int cost;
	bool operator <(const edge &b) const {//将边以权值从小到大的形式排
		return cost < b.cost;
	}
}buf[5000];
int tree[100];
int find(int x) {//之前写成递归形式会爆栈,所以写成非递归
	int ret;
	int tmp=x;
	while (tree[x] != -1) x = tree[x];
	ret = x;
	x = tmp;
	while (tree[x] != -1)
	{
		int t = tree[x];
		tree[x] = ret;
		x = t;
	}
	return ret;
}
int main()
{
	int n;
	while (cin >> n) {
		if (n == 0) break;
		int m;
		cin >> m;
		for (int i = 0;i < n;i++)
			cin>> buf[i].a >> buf[i].b >> buf[i].cost;
		for (int i = 1;i <= m;i++) tree[i] = -1;
		sort(buf, buf + n);
		int ans = 0;
		int count = 0;
		for (int i = 0;i < n;i++)
		{
			int a = find(buf[i].b);
			int b = find(buf[i].a);
			if (a != b) {
				tree[a] = b;
				ans += buf[i].cost;
			}
		}
		for (int i = 1;i <= m;i++)
		{
			if (tree[i] == -1) count++;//用联通分量来判断是否合成了一个最小生成树。
		}
		if (count == 1) cout << ans << endl;
		else cout << "?" << endl;
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值