|
| 1 | +```java |
| 2 | +import java.io.BufferedReader; |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStreamReader; |
| 5 | +import java.util.Iterator; |
| 6 | +import java.util.StringTokenizer; |
| 7 | + |
| 8 | +public class Main { |
| 9 | + private static class WeightedUF{ |
| 10 | + int[] ids; |
| 11 | + int[] size; |
| 12 | + public WeightedUF(int v) { |
| 13 | + ids = new int[v]; |
| 14 | + size = new int[v]; |
| 15 | + for (int i = 0; i < ids.length; i++) { |
| 16 | + ids[i] = i; |
| 17 | + size[i] = 1; |
| 18 | + } |
| 19 | + } |
| 20 | + public int root(int a) { |
| 21 | + while(a != ids[a]) |
| 22 | + a = ids[a]; |
| 23 | + return a; |
| 24 | + } |
| 25 | + public void union(int a, int b) { |
| 26 | + int g, l; |
| 27 | + if(size[a] >= size[b]) { |
| 28 | + g = a; |
| 29 | + l = b; |
| 30 | + }else { |
| 31 | + l = a; |
| 32 | + g = b; |
| 33 | + } |
| 34 | + // b가 더 깊이가 짧음 |
| 35 | + ids[root(b)] = root(a); |
| 36 | + } |
| 37 | + public boolean connected(int a, int b) { |
| 38 | + return root(a) == root(b); |
| 39 | + } |
| 40 | + } |
| 41 | + private static BufferedReader br; |
| 42 | + private static Main.WeightedUF uf; |
| 43 | + private static int m; |
| 44 | + private static int n; |
| 45 | + public static void main(String[] args) throws IOException { |
| 46 | + br = new BufferedReader(new InputStreamReader(System.in)); |
| 47 | + StringBuilder sb = new StringBuilder(); |
| 48 | + String[] temp = br.readLine().split(" "); |
| 49 | + n = Integer.parseInt(temp[0])+1; |
| 50 | + m = Integer.parseInt(temp[1]); |
| 51 | + uf = new WeightedUF(n); |
| 52 | + |
| 53 | + for(int i = 0; i<m; i++) { |
| 54 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 55 | + int command = Integer.parseInt( st.nextToken()); |
| 56 | + int a = Integer.parseInt(st.nextToken()); |
| 57 | + int b = Integer.parseInt(st.nextToken()); |
| 58 | + if(command == 0) { |
| 59 | + // 합집합 |
| 60 | + uf.union(a, b); |
| 61 | + }else { |
| 62 | + // conneted() |
| 63 | + if(uf.connected(a, b)) |
| 64 | + sb.append("YES\n"); |
| 65 | + else |
| 66 | + sb.append("NO\n"); |
| 67 | + } |
| 68 | + } |
| 69 | + System.out.println(sb.toString()); |
| 70 | + br.close(); |
| 71 | + } |
| 72 | + |
| 73 | + |
| 74 | +} |
| 75 | +``` |
0 commit comments