1717번: 집합의 표현
첫째 줄에 n(1 ≤ n ≤ 1,000,000), m(1 ≤ m ≤ 100,000)이 주어진다. m은 입력으로 주어지는 연산의 개수이다. 다음 m개의 줄에는 각각의 연산이 주어진다. 합집합은 0 a b의 형태로 입력이 주어진다. 이는
www.acmicpc.net
풀이과정
유니온 파인드 알고리즘의 가장 대표적인 기본 문제이다.
1. 부모 노드를 찾는 함수
2. 두 부모 노드를 작은 것으로 합치는 함수
3. 부모 노드가 같은지 확인하는 함수
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int n, m;
int parent[1000001];
// 부모 노드를 찾는 함수
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;
}
// 부모 노드가 같은지 확인
void findParent(int a, int b) {
a = getParent(a);
b = getParent(b);
if (a == b) cout << "YES\n";
else cout << "NO\n";
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
parent[i] = i;
}
for (int i = 0; i < m; i++) {
int op, a, b;
cin >> op >> a >> b;
if (!op) unionParent(a, b);
else findParent(a, b);
}
}
'🍞 Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 16562 친구비 c++ (0) | 2022.09.05 |
---|---|
[백준] 1976 여행 가자 c++ (0) | 2022.09.05 |
[백준] 11657 타임머신 c++ (0) | 2022.09.05 |
[백준] 1956 운동 c++ (0) | 2022.09.05 |
[백준] 1719 택배 c++ (0) | 2022.09.05 |