AcWing 859. Kruskal算法求最小生成树
原题链接
简单
作者:
Value
,
2020-05-27 08:17:37
,
所有人可见
,
阅读 454
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
const int N = 2 * 1E5 + 10;
struct node{
int a, b, w;
bool operator < (const node & other) const{
return w < other.w;
}
};
node edge[N];
int n, m;
void read(){
cin >> n >> m;
for(int i = 0; i < m; i ++ ){
scanf("%d%d%d", &edge[i].a, &edge[i].b, &edge[i].w);
}
}
int parent[N];
int find(int t){
if(parent[t] != t) parent[t] = find(parent[t]);
return parent[t];
}
void kruskal(){
for(int i = 0; i < n; i ++ ) parent[i] = i;
sort(edge, edge + m);
int a, b, w;
int res = 0, cnt = 0;
for(int i = 0; i < m; i ++ ){
a = edge[i].a;
b = edge[i].b;
w = edge[i].w;
a = find(a), b = find(b);
if(a != b){
parent[a] = b;
res += w;
cnt ++ ;
}
}
if(cnt == n - 1) cout << res << endl;
else cout << "impossible" << endl;
}
int main(){
read();
kruskal();
return 0;
}