5G网络建设

本文介绍了一个使用C++编写的并查集数据结构和优先队列来解决连接城市的最小成本问题。通过合并城市并计算连接费用,最终确定是否所有城市都连通。
摘要由CSDN通过智能技术生成
#include <algorithm>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
using PRII = pair<int, int>;

class union_find {
	vector<int> data;
	int __size;
public:
	union_find(int n) :__size(n) {
		data.resize(n + 1);
		for (int i = 0; i < n; i++) data[i] = i;
	}
	int find(int which) {
		while (which != data[which]) {
			which = data[which];
		}
		return which;
	}
	void merge(int ua, int ub) {
		ua = find(ua), ub = find(ub);
		if (ua == ub) return;
		data[ub] = ua;
		__size--;
	}
	inline int size() { return __size; }
};

int main() {
	priority_queue<PRII, vector<PRII>, greater<PRII>> pq;
	vector<PRII> will;

	int n, m, ans = 0;
	int a, b, cost, built;
	cin >> n;
	union_find unf(n);
	cin >> m;
	for (int i = 0; i < m; i++) {
		cin >> a >> b >> cost >> built;
		if (built) {
			unf.merge(a, b);
			ans += cost;
		}
		else {
			pq.push({ cost, will.size() });
			will.push_back({ a,b });
		}
	}
	while (!pq.empty()) {
		PRII pcost = pq.top();
		PRII pr = will[pcost.second];
		if (unf.find(pr.first) != unf.find(pr.second)) {
			ans += pcost.first;
			unf.merge(pr.first, pr.second);
		}
		pq.pop();
	}
	if (unf.size() != 1) {
		cout << -1;
		return;
	}
	cout << ans;

}

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值