-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path210304_BOJ_16398.cpp
More file actions
76 lines (57 loc) · 985 Bytes
/
Copy path210304_BOJ_16398.cpp
File metadata and controls
76 lines (57 loc) · 985 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
int N;
vector<pair<int, pair<int, int>>> v;
vector<int> u(1001);
void input() {
cin >> N;
for (int i = 1; i <= N; ++i) {
u[i] = i;
for (int j = 1; j <= N; ++j) {
int c; cin >> c;
if (c == 0)
continue;
if (i < j)
v.push_back({ c ,{i, j} });
}
}
sort(v.begin(), v.end());
}
int Find(int a) {
if (u[a] == a) return a;
else return u[a] = Find(u[a]);
}
bool Union(int a, int b) {
a = Find(a);
b = Find(b);
if (a == b)
return true;
u[b] = a;
return false;
}
void kruskal() {
int cnt = 0;
long long sum = 0;
for (int i = 0; i < v.size(); ++i) {
int x = v[i].second.first;
int y = v[i].second.second;
int cost = v[i].first;
if (!Union(x, y)) {
cnt++;
sum += cost;
}
if (cnt == N - 1)
break;
}
cout << sum << "\n";
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
input();
kruskal();
return 0;
}