POJ 2421 Constructing Roads 最小生成树

题意:求一个图的最小生成树的权值,其中有一些边是已经连通的
思路:在没连通的边中用kruskal求出最小生成树即可

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn = 100005;
const int inf = 0x3f3f3f3f;
int u[maxn], n, q;
struct node {
	int u, v, w;
	node(int u = 0, int v = 0, int w = 0) : u(u), v(v), w(w) {}
}edge[maxn];
bool cmp(node x, node y)
{
	return x.w < y.w;
}
int ufind(int x)
{
	if (u[x] != x) {
		u[x] = ufind(u[x]);
	}
	return u[x];
}
void unite(int x, int y)
{
	u[ufind(x)] = ufind(y);
}
int main()
{
	while (cin >> n) {
		int cnt = 0, k = 0, res = 0;
		for (int i = 1; i <= n; i++) {
			u[i] = i;
			for (int j = 1; j <= n; j++) {
				int w;
				cin >> w;
				if (i != j)
					edge[cnt++] = node(i, j, w);
			}
		}
		cin >> q;
		for (int i = 0; i < q; i++) {
			int x, y;
			cin >> x >> y;
			if (ufind(x) != ufind(y)) {
				unite(x, y);
				k++;
			}
		}
		sort(edge, edge+cnt, cmp);
		for (int i = 0; i < cnt; i++) {
			int x = edge[i].u, y = edge[i].v;
			if (ufind(x) != ufind(y)) {
				unite(x, y);
				k++;
				res += edge[i].w;
			}
			if (k == n-1)
				break;
		}
		cout << res << endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值