1197번: 최소 스패닝 트리
첫째 줄에 정점의 개수 V(1 ≤ V ≤ 10,000)와 간선의 개수 E(1 ≤ E ≤ 100,000)가 주어진다. 다음 E개의 줄에는 각 간선에 대한 정보를 나타내는 세 정수 A, B, C가 주어진다. 이는 A번 정점과 B번 정점이
www.acmicpc.net
풀이과정
크루스칼 알고리즘의 대표적인 문제이다.
연결된 노드의 개수가 정점의 개수 -1개가 되면 노드 연결을 끝내고, 가중치의 합을 출력하면 된다.
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int V, E, A, B, C;
int parent[10001];
vector <pair <int, pair <int, int>>> graph;
int getParent(int x) {
if (parent[x] == x) return x;
return parent[x] = getParent(parent[x]);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> V >> E;
for (int i = 1; i <= V; i++) {
parent[i] = i;
}
for (int i = 0; i < E; i++) {
cin >> A >> B >> C;
graph.push_back({ C, {A, B} });
}
sort(graph.begin(), graph.end());
int sum = 0; // 가중치 합
int num = 0; // 연결된 노드 개수
for (int i = 0; i < E; i++) {
int cost = graph[i].first;
int start = graph[i].second.first;
int end = graph[i].second.second;
int a = getParent(start);
int b = getParent(end);
if (a == b) continue;
if (a < b) parent[b] = a;
else parent[a] = b;
sum += cost;
num++;
if (num == V - 1) {
cout << sum;
break;
}
}
}
'🍞 Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 1449 수리공 항승 c++ (0) | 2022.09.02 |
---|---|
[백준] 1647 도시 분할 c++ (0) | 2022.09.02 |
[백준] 17396 백도어 c++ (0) | 2022.09.02 |
[백준] 10757 큰 수 A+B c++ (0) | 2022.09.02 |
[백준] 11657 타임머신 c++ (0) | 2022.09.02 |