Algorithm/problem
백준 1717번 : 집합의 표현 - Union&Find algorithm
DingCoDing
2022. 1. 18. 18:26
반응형
https://www.acmicpc.net/problem/1717
1717번: 집합의 표현
첫째 줄에 n(1 ≤ n ≤ 1,000,000), m(1 ≤ m ≤ 100,000)이 주어진다. m은 입력으로 주어지는 연산의 개수이다. 다음 m개의 줄에는 각각의 연산이 주어진다. 합집합은 0 a b의 형태로 입력이 주어진다. 이는
www.acmicpc.net
#include <stdio.h>
#include <iostream>
using namespace std;
int unf[1000002];
int Find(int v){
if(v==unf[v]) return v;
else{
return unf[v]=Find(unf[v]);
}
}
void Union(int a, int b){
a = Find(a);
b = Find(b);
if(a!=b){
unf[a] = b;
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int i,n, m,a,b,c;
scanf("%d %d",&n,&m);
for(i=1; i<=n; i++){
unf[i] = i;
}
for(i=0; i<m; i++){
scanf("%d %d %d", &a,&b,&c);
if(a==1){
int v1 = Find(b);
int v2 = Find(c);
if(v1==v2) printf("YES\n");
else printf("NO\n");
}
else{
int v1 = Find(b);
int v2 = Find(c);
if(v1!=v2){
Union(b,c);
}
}
}
}
집합을 나타내는 방법을
union & find 알고리즘을 이용하여 풀 수 있다.
반응형