-
Notifications
You must be signed in to change notification settings - Fork 2
/
Main.java
52 lines (42 loc) Β· 1.43 KB
/
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package Graph.P1717;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int N, M;
static int a, b;
static int[] root;
public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream("src/Graph/P1717/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
root = new int[N+1];
for (int i = 0; i <= N; i++) {
root[i] = i;
}
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
int command = Integer.parseInt(st.nextToken());
a = Integer.parseInt(st.nextToken());
b = Integer.parseInt(st.nextToken());
if (command == 0) {
union(a, b);
} else if (command == 1) {
if (find(a) == find(b)) System.out.println("YES");
else System.out.println("NO");
}
}
}
static void union(int a, int b) {
int aRoot = find(a);
int bRoot = find(b);
root[bRoot] = aRoot;
}
static int find(int a) {
if (root[a] == a) return a;
return root[a] = find(root[a]);
}
}