-
[백준] 1717 집합의 표현ALGORITHM/BOJ 2021. 8. 14. 19:42
https://www.acmicpc.net/problem/1717
2021-08-14
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import java.io.*;import java.util.*;public class Main1717 {public static int[] parent;public static int n, m;public static int find(int x) {if(x == parent[x]) return x;return parent[x] = find(parent[x]);}public static void union(int x, int y) { // y > xx = find(x);y = find(y);if(x != y) parent[y] = x;}public static void main(String[] args) throws IOException {BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));StringTokenizer st = new StringTokenizer(bf.readLine());n = Integer.parseInt(st.nextToken());m = Integer.parseInt(st.nextToken());parent = new int[n+1];for(int i = 1; i <= n; i++) parent[i] = i; // initfor(int i = 0;i < m; i++) {st = new StringTokenizer(bf.readLine());int op = Integer.parseInt(st.nextToken());int a = Integer.parseInt(st.nextToken());int b = Integer.parseInt(st.nextToken());if(op == 0) { //unionif(a > b) {int tmp = b;b = a;a = tmp;}union(a, b);} else { // findif(find(a) == find(b)) System.out.println("YES");else System.out.println("NO");}}}}cs #문제풀이
Union-find
'ALGORITHM > BOJ' 카테고리의 다른 글
[백준] 2075 N번째 큰 수 (0) 2021.09.26 [백준] 10159 저울 (0) 2021.08.31 [백준] 1074 Z (0) 2021.07.13 [백준] 2630 색종이 만들기 (0) 2021.07.09 [백준] 13913 숨바꼭질 4 (0) 2021.07.09