-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path행성연결.cpp
50 lines (46 loc) · 1.13 KB
/
행성연결.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
// BOJ # 16398 행성연결
// 거리가 짧은 순으로 정렬 후, union find로 부모가 같지 않다면 플로우 설치
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
struct node {
int x, y, cost;
};
int n, tmp, parents[1000];
vector<node> cost;
bool cmp(node a, node b) {
return a.cost < b.cost;
}
int find(int x) {
if (x == parents[x]) return x;
int p = find(parents[x]);
parents[x] = p;
return p;
}
void unions(int x, int y) {
x = find(x);
y = find(y);
parents[y] = x;
}
int main() {
long long answer = 0;
int lineCnt = 0;
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> tmp;
if (i < j) cost.push_back({i, j, tmp});
}
}
for (int i = 0; i < n; i++) parents[i] = i;
sort(cost.begin(), cost.end(), cmp);
for (auto elem : cost) {
if (lineCnt == n - 1) break;
if (find(elem.x) == find(elem.y)) continue;
unions(elem.x, elem.y);
answer += elem.cost;
lineCnt++;
}
cout << answer;
}