1+ #include < bits/stdc++.h>
2+
3+ using namespace std ;
4+
5+ // 노드의 개수(V)와 간선(Union 연산)의 개수(E)
6+ // 노드의 개수는 최대 100,000개라고 가정
7+ int v, e;
8+ int parent[100001 ]; // 부모 테이블 초기화하기
9+ // 모든 간선을 담을 리스트와, 최종 비용을 담을 변수
10+ vector<pair<int , pair<int , int > > > edges;
11+ int result = 0 ;
12+
13+ // 특정 원소가 속한 집합을 찾기
14+ int findParent (int x) {
15+ // 루트 노드가 아니라면, 루트 노드를 찾을 때까지 재귀적으로 호출
16+ if (x == parent[x]) return x;
17+ return parent[x] = findParent (parent[x]);
18+ }
19+
20+ // 두 원소가 속한 집합을 합치기
21+ void unionParent (int a, int b) {
22+ a = findParent (a);
23+ b = findParent (b);
24+ if (a < b) parent[b] = a;
25+ else parent[a] = b;
26+ }
27+
28+ int main (void ) {
29+ cin >> v >> e;
30+
31+ // 부모 테이블상에서, 부모를 자기 자신으로 초기화
32+ for (int i = 1 ; i <= v; i++) {
33+ parent[i] = i;
34+ }
35+
36+ // 모든 간선에 대한 정보를 입력 받기
37+ for (int i = 0 ; i < e; i++) {
38+ int a, b, cost;
39+ cin >> a >> b >> cost;
40+ // 비용순으로 정렬하기 위해서 튜플의 첫 번째 원소를 비용으로 설정
41+ edges.push_back ({cost, {a, b}});
42+ }
43+
44+ // 간선을 비용순으로 정렬
45+ sort (edges.begin (), edges.end ());
46+
47+ // 간선을 하나씩 확인하며
48+ for (int i = 0 ; i < edges.size (); i++) {
49+ int cost = edges[i].first ;
50+ int a = edges[i].second .first ;
51+ int b = edges[i].second .second ;
52+ // 사이클이 발생하지 않는 경우에만 집합에 포함
53+ if (findParent (a) != findParent (b)) {
54+ unionParent (a, b);
55+ result += cost;
56+ }
57+ }
58+
59+ cout << result << ' \n ' ;
60+ }
0 commit comments