Skip to content

Commit

Permalink
solve : 1717 집합의 표현
Browse files Browse the repository at this point in the history
  • Loading branch information
wwan13 committed Nov 23, 2024
1 parent 4a6f422 commit 3231cb2
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions java/src/boj1717/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package boj1717;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

private static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

private static int[] parents;

public static void main(String[] args) {
String[] nm = readLine().split(" ");
int n = Integer.parseInt(nm[0]);
int m = Integer.parseInt(nm[1]);

parents = new int[n + 1];
for (int i = 0; i < n + 1; i++) {
parents[i] = i;
}

while (m-- > 0) {
String[] line = readLine().split(" ");
int command = Integer.parseInt(line[0]);
int x = Integer.parseInt(line[1]);
int y = Integer.parseInt(line[2]);

if (command == 0) {
union(x, y);
} else if (command == 1) {
if (find(x) == find(y)) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
}

private static void union(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX != rootY) {
parents[rootY] = parents[rootX];
}
}

private static int find(int x) {
if (parents[x] != x) {
parents[x] = find(parents[x]);
}
return parents[x];
}

private static String readLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

0 comments on commit 3231cb2

Please sign in to comment.