-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path14_kruskalAlgorithm.cpp
81 lines (69 loc) ยท 1.85 KB
/
14_kruskalAlgorithm.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// https://www.youtube.com/watch?v=LQ3JHknGy8c&list=PLRx0vPvlEmdDHxCvAQS1_6XV4deOwfVrz&index=19
// ํฌ๋ฃจ์ค์นผ ์๊ณ ๋ฆฌ์ฆ์ ๊ฐ์ฅ ์ ์ ๋น์ฉ์ผ๋ก ๋ชจ๋ ๋
ธ๋๋ฅผ ์ฐ๊ฒฐํ๊ธฐ ์ํด ์ฌ์ฉํ๋ ์๊ณ ๋ฆฌ์ฆ
// ์ต์ ๋น์ฉ ์ ์ฅ ํธ๋ฆฌ
int getParent(int parent[], int x) {
if (parent[x] == x) return x;
return parent[x] = getParent(parent, parent[x]);
}
void unionParent(int parent[], int a, int b) {
a = getParent(parent, a);
b = getParent(parent, b);
if (a < b) 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;
}
class Edge {
public:
int node[2];
int distance;
Edge(int a, int b, int distance) {
this->node[0] = a;
this->node[1] = b;
this->distance = distance;
}
};
bool compare(Edge a,Edge b){
return a.distance < b.distance;
}
int main(void) {
int n = 7;
int m = 11;
vector<Edge> v;
v.push_back(Edge(1, 7, 12));
v.push_back(Edge(1, 4, 28));
v.push_back(Edge(1, 2, 67));
v.push_back(Edge(1, 5, 17));
v.push_back(Edge(2, 4, 24));
v.push_back(Edge(2, 5, 62));
v.push_back(Edge(3, 5, 20));
v.push_back(Edge(3, 6, 37));
v.push_back(Edge(4, 7, 13));
v.push_back(Edge(5, 6, 45));
v.push_back(Edge(5, 7, 73));
// ๊ฐ์ ์ ๋น์ฉ์ ๊ธฐ์ค์ผ๋ก ์ค๋ฆ์ฐจ์ ์ ๋ ฌ
sort(v.begin(), v.end(), compare);
// ๊ฐ ์ ์ ์ด ํฌํจ๋ ๊ทธ๋ํ๊ฐ ์ด๋์ธ์ง ์ ์ฅ
int parent[7];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
int sum = 0;
for (int i = 0; i < v.size(); i++) {
// ์ฌ์ดํด์ด ๋ฐ์ํ์ง ์๋ ๊ฒฝ์ฐ ๊ทธ๋ํ์ ํฌํจ
if (!findParent(parent, v[i].node[0] - 1, v[i].node[1] - 1)) {
sum += v[i].distance;
unionParent(parent, v[i].node[0] - 1, v[i].node[1] - 1);
}
}
printf("%d\n", sum);
return 0;
}