-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBOJ1647.cpp
65 lines (58 loc) · 1.18 KB
/
BOJ1647.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
//
// Created by ÀüÇüÁø on 2019-03-31.
//
#include <cstdio>
#include <algorithm>
using namespace std;
struct HOUSE {
int a;
int b;
int c;
};
HOUSE house[1000001];
int parent[100001];
int sum = 0;
int n, m;
bool cmp(HOUSE l1, HOUSE l2) {
return l1.c < l2.c;
}
int getParent(int parent[], int x) {
if (parent[x] == x)
return x;
return parent[x] = getParent(parent, parent[x]);
}
int unionParent(int parent[], int a, int b) {
a = getParent(parent, a);
b = getParent(parent, b);
if (a < b)
return parent[b] = a;
else parent[a] = b;
}
int findParent(int parent[], int a, int b) {
a = getParent(parent, a);
b = getParent(parent, b);
if (a == b)
return 1;
return 0;
}
int main() {
scanf_s("%d %d", &n, &m);
for (int i = 0; i < m; i++)
scanf_s("%d %d %d", &house[i].a, &house[i].b, &house[i].c);
for (int i =0; i < n; i++)
parent[i] = i;
int idx = 0;
sort(house, house+m, cmp);
for (int i = 0; i < m; i++) {
if (!findParent(parent, house[i].a, house[i].b)) {
idx++;
sum += house[i].c;
unionParent(parent, house[i].a, house[i].b);
}
if (idx == n - 2) {
break;
}
}
printf("%d", sum);
return 0;
}