-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkruskal.cpp
More file actions
62 lines (62 loc) · 898 Bytes
/
Copy pathkruskal.cpp
File metadata and controls
62 lines (62 loc) · 898 Bytes
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
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define N 5000
#define M 200005
int n,m;
int head[N],to[M],val[M],nex[M],cnt,ans;
void add(int u,int v,int w)
{
to[++cnt]=v;
val[cnt]=w;
nex[cnt]=head[u];
head[u]=cnt;
return;
}
struct E{
int u;int v;int w;
}edge[M];
bool cmp(E x,E y)
{
return x.w<y.w;
}
int f[N];
int find(int x)
{
if(f[x]==x)return x;
return f[x]=find(f[x]);
}
void merge(int x,int y)
{
x=find(f[x]);
y=find(f[y]);
f[x]=y;
return;
}
bool ck(int x,int y)
{
return find(x)==find(y);
}
void init()
{
for(int i=1;i<=m;i++)
{
cin>>edge[i].u>>edge[i].v>>edge[i].w;
}
sort(edge+1,edge+m+1,cmp);
for(int i=1;i<=n;i++)f[i]=i;
for(int i=1;i<=m;i++)
{
if(ck(edge[i].u,edge[i].v))continue;
add(edge[i].u,edge[i].v,edge[i].w);
merge(edge[i].u,edge[i].v);
ans+=edge[i].w;
}
}
signed main()
{
cin>>n>>m;
init();
cout<<ans<<endl;
return 0;
}