Skip to content

Commit 61450f5

Browse files
authored
Kruskal算法求最小生成树
1 parent 4b6c85a commit 61450f5

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

Kruskal.cpp

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
#include <cstdio>
2+
#include <algorithm>
3+
4+
#define VERTEX_COUNT 100000
5+
#define EDGE_COUNT 100000
6+
7+
typedef long long ll;
8+
9+
using namespace std;
10+
11+
struct edge
12+
{
13+
int u, v, w;
14+
}E[EDGE_COUNT];
15+
16+
int ivc, iec;
17+
18+
int fa[VERTEX_COUNT], size[VERTEX_COUNT];
19+
20+
bool E_cmp(edge x, edge y)
21+
{
22+
return x.w < y.w;
23+
}
24+
25+
void init_dsu()
26+
{
27+
for (int i = 1; i <= ivc; i++)
28+
{
29+
fa[i] = i;
30+
size[i] = 1;
31+
}
32+
}
33+
34+
int getrt(int x)
35+
{
36+
if (fa[x] == x)
37+
{
38+
return x;
39+
}
40+
return (fa[x] = getrt(fa[x]));
41+
}
42+
43+
void merge(int rtx, int rty)
44+
{
45+
if (size[rtx] < size[rty])
46+
{
47+
fa[rtx] = rty;
48+
}
49+
else
50+
{
51+
fa[rty] = rtx;
52+
}
53+
}
54+
55+
ll Kruskal()
56+
{
57+
int cnt = 1;
58+
ll wtotal = 0;
59+
for (int i = 0; i < iec && cnt < ivc; i++)
60+
{
61+
int rtu = getrt(E[i].u), rtv = getrt(E[i].v);
62+
if (rtu != rtv)
63+
{
64+
merge(rtu, rtv);
65+
cnt++;
66+
wtotal += E[i].w;
67+
}
68+
}
69+
return wtotal;
70+
}
71+
72+
int main()
73+
{
74+
scanf("%d%d", &ivc, &iec);
75+
init_dsu();
76+
for (int i = 0; i < iec; i++)
77+
{
78+
scanf("%d%d%d", &E[i].u, &E[i].v, &E[i].w);
79+
}
80+
sort(E, E + iec, E_cmp);
81+
ll res = Kruskal();
82+
printf("%lld", res);
83+
return 0;
84+
}

0 commit comments

Comments
 (0)