-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCycleGame.java
More file actions
67 lines (59 loc) · 1.75 KB
/
Copy pathCycleGame.java
File metadata and controls
67 lines (59 loc) · 1.75 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package algorithm.baek.graph;
import algorithm.TestCase;
import java.io.*;
import java.text.ParseException;
import java.util.StringTokenizer;
/**
* https://www.acmicpc.net/problem/20040
* 사이클 게임
*/
public class CycleGame implements TestCase {
static int[] parent;
@Override
public void test() throws ParseException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
init(n);
int result = 0;
for (int i = 1; i <= m; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
if (isSameParent(a, b)) {
result = i;
break;
}
union(a, b);
}
bw.write(result + "\n");
bw.flush();
bw.close();
}
public void init(int n) {
parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
public void union(int a, int b) {
int pa = find(a);
int pb = find(b);
if (pa < pb) {
parent[pb] = pa;
} else {
parent[pa] = pb;
}
}
public int find(int a) {
if (parent[a] == a) {
return a;
}
return parent[a] = find(parent[a]);
}
public boolean isSameParent(int a, int b) {
return find(a) == find(b);
}
}