-
Notifications
You must be signed in to change notification settings - Fork 439
/
Kruskal.cpp
84 lines (72 loc) · 1.02 KB
/
Kruskal.cpp
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <cstdio>
#include <algorithm>
#define VERTEX_COUNT 100000
#define EDGE_COUNT 100000
typedef long long ll;
using namespace std;
struct edge
{
int u, v, w;
}E[EDGE_COUNT];
int ivc, iec;
int fa[VERTEX_COUNT], size[VERTEX_COUNT];
bool E_cmp(edge x, edge y)
{
return x.w < y.w;
}
void init_dsu()
{
for (int i = 1; i <= ivc; i++)
{
fa[i] = i;
size[i] = 1;
}
}
int getrt(int x)
{
if (fa[x] == x)
{
return x;
}
return (fa[x] = getrt(fa[x]));
}
void merge(int rtx, int rty)
{
if (size[rtx] < size[rty])
{
fa[rtx] = rty;
}
else
{
fa[rty] = rtx;
}
}
ll Kruskal()
{
int cnt = 1;
ll wtotal = 0;
for (int i = 0; i < iec && cnt < ivc; i++)
{
int rtu = getrt(E[i].u), rtv = getrt(E[i].v);
if (rtu != rtv)
{
merge(rtu, rtv);
cnt++;
wtotal += E[i].w;
}
}
return wtotal;
}
int main()
{
scanf("%d%d", &ivc, &iec);
init_dsu();
for (int i = 0; i < iec; i++)
{
scanf("%d%d%d", &E[i].u, &E[i].v, &E[i].w);
}
sort(E, E + iec, E_cmp);
ll res = Kruskal();
printf("%lld", res);
return 0;
}