C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100010
#define M 200010
struct Edge {
int from, to;
int weight;
} edges[M];
int n, m, father[N];
void init() {
scanf("%d%d", &n, &m);
for (int i = 0; i < m; ++i) {
scanf("%d%d%d", &edges[i].from, &edges[i].to, &edges[i].weight);
}
for (int i = 1; i <= n; ++i) {
father[i] = i;
}
}
int findFather(int x) {
if (father[x] != x) {
father[x] = findFather(father[x]);
}
return father[x];
}
int cmpEdge(const void *lhs, const void *rhs) {
struct Edge *pL = (struct Edge*) lhs, *pR = (struct Edge*) rhs;
if (pL->weight > pR->weight) {
return 1;
} else if (pL->weight < pR->weight) {
return -1;
}
return 0;
}
int Kruskal() {
int ans = 0, cnt = 0;
qsort(edges, m, sizeof(struct Edge), cmpEdge);
for (int i = 0; i < m; ++i) {
int u = edges[i].from, v = edges[i].to, w = edges[i].weight;
int uFather = findFather(u), vFather = findFather(v);
if (uFather == vFather) {
continue;
}
father[uFather] = vFather;
ans += w;
++cnt;
if (cnt == n-1) {
break;
}
}
return cnt == n-1 ? ans : -1;
}
int main() {
init();
int res = Kruskal();
if (res == -1) {
puts("impossible");
} else {
printf("%d\n", res);
}
return 0;
}
C++
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
const int N = 100010;
struct Edge {
int from_, to_;
int weight_;
Edge(int from, int to, int weight) : from_(from), to_(to), weight_(weight) {}
bool operator>(const Edge& rhs) const {
return weight_ > rhs.weight_;
}
};
int n, m;
vector<int> father(N);
priority_queue<Edge, vector<Edge>, greater<Edge> > pq;
void init() {
cin >> n >> m;
int u, v, w;
while (m--) {
cin >> u >> v >> w;
pq.emplace(u, v, w);
}
for (int i = 1; i <= n; ++i) {
father[i] = i;
}
}
int findFather(int x) {
if (father[x] != x) {
father[x] = findFather(father[x]);
}
return father[x];
}
int Kruskal() {
int ans = 0, cnt = 0;
while (!pq.empty()) {
auto [u, v, w] = pq.top();
pq.pop();
int uFather = findFather(u), vFather = findFather(v);
if (uFather == vFather) {
continue;
}
father[uFather] = vFather;
ans += w;
++cnt;
if (cnt == n-1) {
break;
}
}
return cnt == n-1 ? ans : -1;
}
int main() {
init();
if (int res = Kruskal(); res == -1) {
cout << "impossible" << endl;
} else {
cout << res << endl;
}
return 0;
}