最小生成树

kruskal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include<bits/stdc++.h>
using namespace std;
int n,m;
struct edge{
int u,v;
int w;
}e[200001];
int fa[5001];
int tot;
void add(int x,int y,int z)
{
e[++tot].u=x;
e[tot].v=y;
e[tot].w=z;
return ;
}
bool cmp(edge a,edge b)
{
return a.w<b.w;
}
int get_father(int x)
{
if(fa[x]==x)
{
return x;
}
else
{
fa[x]=get_father(fa[x]);
return fa[x];
}
return 0;
}
void add_into(int x,int y)
{
fa[get_father(y)]=get_father(x);
return ;
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
fa[i]=i;
}
for(int i=1;i<=m;i++)
{
int x,y,z;
cin>>x>>y>>z;
add(x,y,z);
}
sort(e+1,e+tot+1,cmp);
int ans=0;
int cnt=0;
for(int i=1;i<=tot;i++)
{
if(get_father(e[i].u)!=get_father(e[i].v))
{
cnt++;
ans+=e[i].w;
add_into(e[i].u,e[i].v);
}
if(cnt==n-1)
{
break;
}
}
cout<<ans<<endl;
return 0;
}