https://www.acmicpc.net/problem/1717
1717번: 집합의 표현
초기에 $n+1$개의 집합 $\{0\}, \{1\}, \{2\}, \dots , \{n\}$이 있다. 여기에 합집합 연산과, 두 원소가 같은 집합에 포함되어 있는지를 확인하는 연산을 수행하려고 한다. 집합을 표현하는 프로그램을 작
www.acmicpc.net
union find 알고리즘 문제... 사실 알고리즘 외워서 푸는 문젠 그닥 좋아하진않는데 일단 최소스패닝 트리의 크루스칼 알고리즘 근간이 되는거라 ... ㅎ
다시 공부하니 새롭네요 ㅎ
import java.util.*;
import java.lang.*;
import java.lang.reflect.Array;
import java.io.*;
public class Main {
private int[]parent;
public Main(int size) {
parent =new int[size];
for(int i=0;i<size;i++) {
parent[i]=i;
}
}
public int find(int x) {
if(x!=parent[x]) {
parent[x]=find(parent[x]);
}
return parent[x];
}
public void union(int x,int y) {
int rootX=find(x);
int rootY=find(y);
if(rootX!=rootY) {
parent[rootX]=rootY;
}
}
public static void main(String[] args) throws Exception {
Scanner scan =new Scanner(System.in);
//초기에 n+1개의 집합 {0},1...n
//여기에 합집합연산과, 두 원소가 같은 집합에 포함되어 잇는지를 확인하는 연산수행
int n=scan.nextInt();
int m=scan.nextInt();
Main uf=new Main(n+1);
ArrayList<String>anw=new ArrayList<>();
for(int i=0;i<m;i++) {
int c=scan.nextInt();
int a=scan.nextInt();
int b=scan.nextInt();
if(c==0) {
//합집합
uf.union(a, b);
}else if(c==1) {
//체크
if(uf.find(a)==uf.find(b)) {
anw.add("YES");
}else {
anw.add("NO");
}
}
}
for(int i=0;i<anw.size();i++) {
System.out.println(anw.get(i));
}
}
}
'알고리즘 공부' 카테고리의 다른 글
백준 스도쿠 (0) | 2023.12.18 |
---|---|
백준 여행가자 (0) | 2023.12.13 |
백준 뱀과 사다리 게임 (1) | 2023.12.12 |
백준 주사위 굴리기 (1) | 2023.12.11 |
백준 뱀 (0) | 2023.12.05 |