728x90
반응형
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>
using namespace std;
int v, e;
int parent[10001];
int getParent(int x){
if(parent[x] == x) return x;
return parent[x] = getParent(parent[x]);
}
void unionParent(int a, int b){
a = getParent(a);
b = getParent(b);
if(a > b) parent[a] = b;
else parent[b] = a;
}
bool findParent(int a, int b){
a = getParent(a);
b = getParent(b);
if(a == b) return true;
else return false;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> v >> e;
vector<pair<int, pair<int, int>>> vt;
for(int i = 0; i < e; i++){
int a, b, c;
cin >> a >> b >> c;
vt.push_back({c, {a, b}});
}
sort(vt.begin(), vt.end());
for(int i = 1; i <= v; i++)
parent[i] = i;
int answer = 0;
for(int i = 0; i < e; i++){
if(!findParent(vt[i].second.first, vt[i].second.second)){
answer += vt[i].first;
unionParent(vt[i].second.first, vt[i].second.second);
}
}
cout << answer << endl;
return 0;
}
Kruscal 알고리즘으로 해결했다.
728x90
반응형
'Algorithm > BAEKJOON' 카테고리의 다른 글
[BOJ] 2468번 안전 영역 (C++) (0) | 2022.05.25 |
---|---|
[BOJ] 20040번 사이클 게임 (C++) (0) | 2022.05.23 |
[BOJ] 1717번 집합의 표현 (C++) (0) | 2022.05.23 |
[BOJ] 21940번 가운데에서 만나기 (C++) (0) | 2022.05.22 |
[BOJ] 10026번 적록색약 (C++) (0) | 2022.05.19 |