-
Notifications
You must be signed in to change notification settings - Fork 0
/
2668.java
61 lines (47 loc) · 1.13 KB
/
2668.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
53
54
55
56
57
58
59
60
61
import java.io.*;
import java.util.*;
public class Main {
static ArrayList<Integer> ans = new ArrayList<>();
static int numbers[], N;
static boolean visit[];
public static void main(String args[]) throws Exception{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(input.readLine());
numbers = new int[N+1];
visit = new boolean[N+1];
for(int i=1; i<=N; i++) {
numbers[i] = Integer.parseInt(input.readLine());
}
for(int i=1; i<=N; i++) {
if(i == numbers[i]) ans.add(i);
else if(!ans.contains(i)){
visit[i] = true;
if(dfs(i, numbers[i])) {
ans.add(i);
}
}
Arrays.fill(visit, false);
}
Collections.sort(ans);
StringBuilder sb = new StringBuilder();
sb.append(ans.size()+"\n");
for(int n : ans) {
sb.append(n+"\n");
}
System.out.println(sb.toString());
}
private static boolean dfs(int start, int here) {
if(visit[here]) {
if(here == start) {
return true;
}
return false;
}
visit[here] = true;
if(dfs(start, numbers[here])) {
ans.add(here);
return true;
}
return false;
}
}