标签:c++ opera imp out clu put ons ret const
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 100010, E = 200010;
struct edge{
int a, b, w;
bool operator <(const edge &e){
return w < e.w;
}
}edges[E];
int n, m;
int p[N];
int find(int x){
if(x != p[x]) p[x] = find(p[x]);
return p[x];
}
int kruskal(){
int res = 0, cnt = 0;
for(int i = 1; i <= m; i ++){
int a = edges[i].a, b = edges[i].b, w = edges[i].w;
if(find(a) != find(b)){
p[find(a)] = find(b);
cnt ++;
res += w;
}
}
if(cnt < n - 1) res = -1;
return res;
}
int main(){
cin >> n >> m;
for(int i = 1; i <= n; i ++) p[i] = i;
for(int i = 1; i <= m; i ++){
int a, b, w;
cin >> a >> b >> w;
edges[i] = {a, b, w};
}
sort(edges + 1, edges + m + 1);
int k = kruskal();
if(~ k) cout << k;
else puts("impossible");
return 0;
}
标签:c++ opera imp out clu put ons ret const
原文地址:https://www.cnblogs.com/tomori/p/13584741.html