[백준] 1717번 - 집합의 표현

LJ-hyeok·2022년 11월 12일

알고리즘

목록 보기
4/6

beakjoon

백준 1717번 집합의 표현

https://www.acmicpc.net/problem/1717


코드

#include<iostream>
using namespace std;

int p[1000003];

int find(int x){
	if(p[x]==x)	return x;
	return p[x] = find(p[x]);
}

void Union(int a,int b){
	a = find(a);
	b = find(b);
	if(a==b)	return;
	p[a] = b;
}

int main(){ios_base::sync_with_stdio(false);cin.tie(NULL);
	int n,m;
	cin >> n >> m;
	for(int i=1;i<=n;i++)	p[i] = i;
	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";
		}

		if(t==0){
			Union(a,b);
		}
	}
}

풀이

분리 집합을 이용한 기분 문제

profile
위이이잉

0개의 댓글