666
2024-09-11 21:11:39
发布于:广东
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Edge {
int src, dest, cost;
bool operator<(const Edge& e) const {
return cost < e.cost;
}
};
class UnionFind {
public:
vector<int> parent, rank;
UnionFind(int n) : parent(n), rank(n, 0) {
for (int i = 0; i < n; ++i) parent[i] = i;
}
int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
void unionSet(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX != rootY) {
if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else {
parent[rootY] = rootX;
rank[rootX] += 1;
}
}
}
};
int main() {
int T;
cin >> T;
while (T--) {
int N, E;
cin >> N >> E;
vector<Edge> edges;
for (int i = 0; i < E; ++i) {
int A, B, K;
cin >> A >> B >> K;
edges.push_back({A, B, K});
}
sort(edges.begin(), edges.end());
UnionFind uf(N);
int totalCost = 0;
int edgeCount = 0;
for (auto& edge : edges) {
if (uf.find(edge.src) != uf.find(edge.dest)) {
uf.unionSet(edge.src, edge.dest);
totalCost += edge.cost;
edgeCount++;
if (edgeCount == N - 1) break;
}
}
cout << totalCost << endl;
}
return 0;
}
这里空空如也
有帮助,赞一个