#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;
}
5G网络建设
于 2024-03-21 23:07:35 首次发布
本文介绍了一个使用C++编写的并查集数据结构和优先队列来解决连接城市的最小成本问题。通过合并城市并计算连接费用,最终确定是否所有城市都连通。
摘要由CSDN通过智能技术生成