File tree Expand file tree Collapse file tree 2 files changed +53
-0
lines changed
Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .io .*;
2+ import java .util .*;
3+
4+ /**
5+ * BOJ 1717 집합의 표현
6+ */
7+ public class Main {
8+ public static void main (String [] args ) throws IOException {
9+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
10+ BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (System .out ));
11+
12+ String str1 [] = br .readLine ().split (" " );
13+ int n = Integer .parseInt (str1 [0 ]), m = Integer .parseInt (str1 [1 ]);
14+
15+ int disjoint [] = new int [n +1 ];
16+
17+ for (int i = 0 ; i <=n ; i ++){
18+ disjoint [i ] = i ;
19+ }
20+
21+ for (int i = 0 ; i <m ; i ++){
22+ String str2 [] = br .readLine ().split (" " );
23+ int a = Integer .parseInt (str2 [0 ]), b = Integer .parseInt (str2 [1 ]), c = Integer .parseInt (str2 [2 ]);
24+ if (a == 0 ){
25+ // c 의 부모를 b의 부모로 한다.
26+ link (disjoint , b , c );
27+ }else {
28+ // c의 부모와 b의 부모가 맞다면
29+ if (find (disjoint , b ) == find (disjoint , c ))
30+ bw .write ("YES" );
31+ else
32+ bw .write ("NO" );
33+ bw .write ("\n " );
34+ }
35+ }
36+
37+ bw .flush ();
38+
39+ }
40+ /**
41+ * 트리 구조이기 때문에 루트를 변겅하면 그 밑에것들은 알아서 따라오게 된다.
42+ */
43+ private static void link (int dis [], int x , int y ){
44+ dis [find (dis , y )] = find (dis , x );
45+ }
46+ /**
47+ * 트리 구조에서 루트를 찾기위해 재귀함수를 이용한다.
48+ */
49+ private static int find (int dis [], int x ){
50+ if (dis [x ] == x ) return x ;
51+ else return dis [x ] = find (dis , dis [x ]);
52+ }
53+ }
You can’t perform that action at this time.
0 commit comments