728x90
SMALL
크루스칼 알고리즘은 모르는 이에게 설명하기도 쉽고 이해하기도 쉽다.
unionParent함수에서 일반적으로 부모노드가 더 큰 쪽에 합치지만
일방적으로 첫번째 파라미터인 변수에 union 했다.
코드
// Kruskal Algorithm Using Union & Find
#include <iostream>
#include <algorithm>
using namespace std;
using ll = long long;
const int MAX = 1e7;
int n,m;
int Parent[MAX]; // Parent[node] == parent of node
int getParent(int n) {
if (Parent[n] == n) return n;
else return Parent[n] = getParent(Parent[n]);
}
void unionParent(int n1, int n2) {
n1 = getParent(n1);
n2 = getParent(n2);
if (n1 != n2) Parent[n2] = n1;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++) Parent[i] = i;
for (int i = 0; i < m; i++) {
int k, a, b;
cin >> k >> a >> b;
if (k == 1) {
if (getParent(a) == getParent(b)) cout << "YES\n";
else cout << "NO\n";
}
else unionParent(a, b);
}
return 0;
}
728x90
LIST
'PS > BOJ' 카테고리의 다른 글
백준 2180 (C++) 소방서의 고민 (2) | 2021.09.28 |
---|---|
백준 2581 (C++) 소수 (0) | 2021.09.28 |
백준 10984 (C++) 내 학점을 구해줘 (0) | 2021.09.26 |
백준 4386 (C++) 별자리 만들기 (0) | 2021.09.26 |
백준 7346 (C++) 유전자 함수 (0) | 2021.09.26 |