最小生成树/kruskal- 模板
作者:
殇ベ_11
,
2021-02-03 15:38:02
,
所有人可见
,
阅读 347
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 100000;
const int inf = 0x7fffffff;
struct node{
int a;
int b;
int val;
bool operator < (const node &x) const
{
return x.val>val;
}
}e[N << 1];
int n,m,fa[N << 1];
int find(int x)
{
return fa[x] == x ? x : fa[x] = find(fa[x]);
}
int read()
{
char c = getchar();
int f = 1, x = 0;
while(!isdigit(c)) {if(c == '-') f = -1;c = getchar();}
while(isdigit(c)){x = x * 10 + c - 48;c = getchar();}
return x * f;
}
int ans,cnt;
void kru()
{
sort(e+1,e+m+1);
for(int i=1;i<=m;i++)
{
int x,y;
x = find(e[i].a);
y = find(e[i].b);
if(x == y) continue;
fa[x]=y;
ans+=e[i].val;
cnt++;
if(cnt>=n-1) break;
}
if(cnt<n-1)
{
puts("impossible");
exit(0);
}
}
int main()
{
n = read(),m = read();
for(int i=1;i<=m;i++)
{
e[i].a = read();
e[i].b = read();
e[i].val = read();
}
for(int i=1;i<=n;i++) fa[i]=i;
kru();
printf("%d",ans);
}