SOLUTION INFO
C++ · main.cpp
- 작성자
- tony9402
- 공동 작성자
- 없음
#include<bits/stdc++.h>
using namespace std;
int uf[1000005];
int find(int x) {
if(uf[x] < 0) return x;
return uf[x] = find(uf[x]);
}
bool merge(int a, int b) {
a = find(a);
b = find(b);
if(a == b)return false;
uf[b] = a;
return true;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int N, M; cin >> N >> M;
for(int i=0;i<=N;i++) uf[i] = -1;
for(int i=0;i<M;i++) {
int t, a, b; cin >> t >> a >> b;
if(t == 1) {
if(find(a) == find(b)) cout << "YES\n";
else cout << "NO\n";
}
else merge(a, b);
}
return 0;
}
SOLUTION DESCRIPTION
풀이 설명
등록된 풀이 설명이 없습니다.
SOLUTION INFO
Python · main.py
- 작성자
- cieske
- 공동 작성자
- 없음
import sys
def input():
return sys.stdin.readline().rstrip()
n, m = map(int, input().split())
dis_set = [-1]*(n+1)
#Disjoint set 관련 함수
def upward(x, update_lst):
if dis_set[x] < 0: # 해당 disjoint set의 최상단 root를 찾음
return x
# x가 root가 아니라면 update_lst에 추가하고 root를 찾아감
update_lst.append(x)
return upward(dis_set[x], update_lst)
def find(x):
update_lst = [] # x가 속한 disjoint set에서 path compression을 위해 root update가 필요한 node set
root = upward(x, update_lst) # x가 속한 disjoint set의 root
for idx in update_lst: # Path compression
dis_set[idx] = root
return root
def union(x, y):
x_root = find(x)
y_root = find(y)
if x_root != y_root: #두 node의 root가 다르다면 -> 합쳐야 함
dis_set[y_root] = x_root
for _ in range(m):
oper, x, y = map(int, input().split())
if oper: # Check
if find(x) == find(y):
print("YES")
else:
print("NO")
else: # Union
union(x, y)
SOLUTION DESCRIPTION
풀이 설명
등록된 풀이 설명이 없습니다.