Skip to content

Commit 51162f6

Browse files
committed
[BOJ] 1197 최소 스패닝 트리 (G4)
1 parent 0505dc0 commit 51162f6

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

박예진/2주차/260105.cpp

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#include <iostream>
2+
#include <algorithm>
3+
#include <vector>
4+
5+
using namespace std;
6+
7+
/*
8+
크루스칼 알고리즘 - 유니온 파인드
9+
0. 부모 노드 초기화
10+
1. 가중치 기준으로 간선 오름차순
11+
2. 모든 간선 탐색
12+
3. 작은 가중치를 가진 노드로 부모 노드 변경
13+
*/
14+
15+
struct Edge {
16+
int a, b, c;
17+
};
18+
19+
bool cmp(const Edge &e1, const Edge &e2) {
20+
return e1.c < e2.c;
21+
}
22+
23+
int V, E;
24+
int parent[10001];
25+
vector<Edge> edges;
26+
27+
int getParent(int x) {
28+
if (parent[x] == x) return x;
29+
else return parent[x] = getParent(parent[x]);
30+
}
31+
32+
int kruskal() {
33+
// 간선 가중치 오름차순
34+
sort(edges.begin(), edges.end(), cmp);
35+
36+
int sum = 0; // 가중치 합
37+
int num = 0; // 연결된 간선 개수
38+
39+
for(int i = 0; i < E; i++){
40+
int pa = getParent(edges[i].a);
41+
int pb = getParent(edges[i].b);
42+
43+
if (pa == pb) continue;
44+
if (pa < pb) parent[pb] = pa;
45+
else parent[pa] = pb;
46+
47+
sum += edges[i].c;
48+
num++;
49+
50+
if (num == V - 1) return sum;
51+
}
52+
return -1;
53+
}
54+
55+
56+
int main(){
57+
ios_base::sync_with_stdio(false);
58+
cin.tie(NULL); cout.tie(NULL);
59+
60+
cin >> V >> E;
61+
// 부모 노드 초기화
62+
for(int i = 1; i <= V; i++){
63+
parent[i] = i;
64+
}
65+
for(int i = 0; i < E; i++){
66+
int A, B, C;
67+
cin >> A >> B >> C;
68+
edges.push_back({A, B, C});
69+
}
70+
71+
cout << kruskal();
72+
}

0 commit comments

Comments
 (0)