File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed
Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change 1+ ``` java
2+ import java.io.* ;
3+ import java.util.* ;
4+
5+ public class Main {
6+ static int N ,M ;
7+ static int [] root;
8+
9+ public static void main (String [] args ) throws IOException {
10+ BufferedReader br = new BufferedReader (new InputStreamReader (System . in));
11+ BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (System . out));
12+ StringTokenizer st = new StringTokenizer (br. readLine());
13+ N = Integer . parseInt(st. nextToken());
14+ M = Integer . parseInt(st. nextToken());
15+ root = new int [N + 1 ];
16+
17+ for (int i = 0 ; i <= N ; i++ ) {
18+ root[i] = i;
19+ }
20+
21+ for (int i = 0 ; i < M ; i++ ) {
22+ st = new StringTokenizer (br. readLine());
23+
24+ int cmd = Integer . parseInt(st. nextToken());
25+ int a = Integer . parseInt(st. nextToken());
26+ int b = Integer . parseInt(st. nextToken());
27+
28+ if (cmd == 0 ){ // 합
29+ union(a,b);
30+ }else if (cmd == 1 ){ // 같이 있나?
31+ if (find(a) == find(b)){
32+ bw. write(" yes\n " );
33+ }else {
34+ bw. write(" no\n " );
35+ }
36+ }
37+ }
38+
39+ bw. close();
40+ }
41+
42+ static int find (int cur ){
43+ if (cur == root[cur]) return cur;
44+ else {
45+ return root[cur] = find(root[cur]);
46+ }
47+ }
48+ static void union (int a , int b ){
49+ int rootA = find(a);
50+ int rootB = find(b);
51+
52+ if (rootA < rootB){
53+ root[rootB] = rootA;
54+ }else {
55+ root[rootA] = rootB;
56+ }
57+ }
58+ }
59+ ```
You can’t perform that action at this time.
0 commit comments