Skip to content

Commit 8412ada

Browse files
authored
Merge pull request #2052 from AlgorithmWithGod/khj20006
[20260330] BOJ / P3 / 마블 / 권혁준
2 parents e71c840 + 94a5ce0 commit 8412ada

1 file changed

Lines changed: 92 additions & 0 deletions

File tree

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class BOJ2843 {
6+
static class DisjointSet {
7+
int[] root;
8+
DisjointSet(int size) {
9+
root = new int[size+1];
10+
for(int i=0;i<=size;i++) {
11+
root[i] = i;
12+
}
13+
}
14+
15+
int find(int x) {
16+
return x == root[x] ? x : (root[x] = find(root[x]));
17+
}
18+
19+
boolean union(int a, int b) {
20+
int x = find(a), y = find(b);
21+
if(x == y) return false;
22+
root[x] = y;
23+
return true;
24+
}
25+
}
26+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
27+
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
28+
static StringTokenizer st;
29+
30+
static int N, Q;
31+
static int[] arr;
32+
static int[][] queries;
33+
static boolean[] check;
34+
static DisjointSet ds;
35+
36+
public static void main(String[] args) throws Exception {
37+
N = Integer.parseInt(br.readLine());
38+
39+
arr = new int[N+1];
40+
check = new boolean[N+1];
41+
st = new StringTokenizer(br.readLine());
42+
for(int i=1;i<=N;i++) {
43+
arr[i] = Integer.parseInt(st.nextToken());
44+
}
45+
46+
Q = Integer.parseInt(br.readLine());
47+
queries = new int[Q][];
48+
for(int i=0;i<Q;i++) {
49+
st = new StringTokenizer(br.readLine());
50+
int op = Integer.parseInt(st.nextToken());
51+
int x = Integer.parseInt(st.nextToken());
52+
if(op == 2) {
53+
check[x] = true;
54+
}
55+
queries[i] = new int[]{op, x};
56+
}
57+
58+
ds = new DisjointSet(N);
59+
60+
for(int i=1;i<=N;i++) if(!check[i] && arr[i] != 0) {
61+
if(!ds.union(i, arr[i])) {
62+
ds.union(i, 0);
63+
}
64+
}
65+
66+
Stack<String> answer = new Stack<>();
67+
for(int i=Q-1;i>=0;i--) {
68+
int op = queries[i][0], x = queries[i][1];
69+
if(op == 2) {
70+
if(arr[x] != 0 && !ds.union(x, arr[x])) {
71+
ds.union(x, 0);
72+
}
73+
}
74+
else {
75+
int r = ds.find(x);
76+
if(r == 0) {
77+
answer.add("CIKLUS");
78+
}
79+
else {
80+
answer.add(Integer.toString(r));
81+
}
82+
}
83+
}
84+
85+
while(!answer.isEmpty()) {
86+
bw.write(answer.pop() + "\n");
87+
}
88+
89+
bw.close();
90+
}
91+
}
92+
```

0 commit comments

Comments
 (0)