-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkruskal.cpp
More file actions
100 lines (91 loc) · 1.53 KB
/
kruskal.cpp
File metadata and controls
100 lines (91 loc) · 1.53 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
using ll = long long;
struct edge
{
ll x, y, w;
};
int sz[100005], parent[100005];
int n, m;
vector<edge> dscanh;
void init()
{
for (int i = 1; i <= 100000; i++)
{
sz[i] = 1;
parent[i] = i;
}
}
int Find(int u)
{
if (u == parent[u])
return u;
return parent[u] = Find(parent[u]);
}
bool Union(int u, int v)
{
u = Find(u);
v = Find(v);
if (u == v)
return false;
if (sz[u] < sz[v])
{
swap(u, v);
}
sz[u] += sz[v];
parent[v] = u;
return true;
}
void nhap()
{
cin >> n >> m;
for (int i = 0; i < m; i++)
{
ll x, y, w;
cin >> x >> y >> w;
edge e{x, y, w};
dscanh.push_back(e);
}
}
bool cmp(edge a, edge b)
{
return a.w < b.w;
}
void Kruskal()
{
// B1 : Sx danh sach canh
sort(dscanh.begin(), dscanh.end(), cmp);
ll d = 0;
vector<edge> mst; // luu canh cay khung
// B2 : duyet va chon
for (int i = 0; i < m; i++)
{
if (mst.size() == n - 1)
break; // du canh
edge tmp = dscanh[i];
if (Union(tmp.x, tmp.y))
{
d += tmp.w;
mst.push_back(tmp);
}
}
if (mst.size() < n - 1)
{
cout << "IMPOSSIBLE\n";
}
else
{
cout << d << endl;
// for (edge X : mst)
// {
// cout << X.x << ' ' << X.y << ' ' << X.w << endl;
// }
}
}
int main()
{
init();
nhap();
Kruskal();
}