kruskcal
并查集
int find(int x) {
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
kruscal
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1e5 + 10;
int n, m;
int p[N];
struct Edge {
int a, b, w;
bool operator< (const Edge &W) const {
return w < W.w;
}
}edges[N];
int find(int x) {
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main() {
cin >> n >> m;
for(int i = 0; i < m; i ++) {
int a, b, w;
cin >> a >> b >> w;
edges[i] = {a, b, w};
}
for(int i = 1; i <= n; i ++) p[i] = i;
sort(edges, edges + m);
int res = 0, cnt = 0;
for(int i = 0; i < m; i ++) {
int a = edges[i].a, b = edges[i].b, w = edges[i].w;
a = find(a), b = find(b);
if(a != b) {
p[a] = b;
cnt ++ ;
res += w;
}
}
if(cnt < n - 1) puts("impossible");
else cout << res << endl;
return 0;
}
既然都学了 kruskal,建议再看看 kruskal 重构树,很简单。