https://www.acmicpc.net/problem/1197
1197번: 최소 스패닝 트리
첫째 줄에 정점의 개수 V(1 ≤ V ≤ 10,000)와 간선의 개수 E(1 ≤ E ≤ 100,000)가 주어진다. 다음 E개의 줄에는 각 간선에 대한 정보를 나타내는 세 정수 A, B, C가 주어진다. 이는 A번 정점과 B번 정점이
www.acmicpc.net
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
vector<pair<int, pair<int, int>>> vec;
int boss[10001];
int findBoss(int a) {
if (boss[a] == a)
return a;
else
return boss[a] = findBoss(boss[a]);
}
void setUnion(int a, int b) {
a = findBoss(a);
b = findBoss(b);
if (a != b)
boss[b] = a;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int V, E;
cin >> V >> E;
for (int i = 0; i < E; i++) {
int a, b, c;
cin >> a >> b >> c;
vec.push_back(make_pair(c, make_pair(a, b)));
}
sort(vec.begin(), vec.end());
for (int i = 1; i <= V; i++) {
boss[i] = i;
}
int result = 0;
for (int i = 0; i < E; i++) {
int a = vec[i].second.first;
int b = vec[i].second.second;
if (findBoss(a) != findBoss(b)) {
setUnion(a, b);
result += vec[i].first;
}
}
cout << result;
return 0;
}
'APS > 백준' 카테고리의 다른 글
[2252] 줄 세우기 C++ (0) | 2022.04.18 |
---|---|
[5052] 전화번호 목록 (0) | 2022.03.15 |
[21924] 도시 건설 C++ (0) | 2022.03.05 |
[14716] 현수막 C++ (0) | 2022.03.05 |
[10816] 숫자 카드2 C++ (0) | 2022.03.03 |