-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshuffle.txt
55 lines (52 loc) · 1.88 KB
/
shuffle.txt
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
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
public class shuffle {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new FileReader("shuffle.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("shuffle.out")),true);
int x = Integer.parseInt(f.readLine());
StringTokenizer st = new StringTokenizer(f.readLine());
int[] swaps = new int[x];
for(int i=0; i<x; i++){
swaps[i]=Integer.parseInt(st.nextToken())-1;
}
boolean[] processed = new boolean[x];
boolean[] inCycle = new boolean[x];
for(int i=0; i<x; i++){
if(!processed[i]){
HashMap<Integer,Integer> map = new HashMap<>();
ArrayList<Integer> direction = new ArrayList<>();
int iter=0;
int current = i;
boolean cycleFound = false;
while (!map.containsKey(current)&&!processed[current]){
map.put(current,iter);
direction.add(current);
processed[current]=true;
current=swaps[current];
iter++;
if(map.containsKey(current)){
cycleFound=true;
}
}
if(cycleFound){
for(int j = map.get(current); j<iter; j++){
inCycle[direction.get(j)]=true;
}
}
}
}
int ans = 0;
for(int i=0; i<x; i++){
if(inCycle[i]){
System.out.println(i);
ans++;
}
}
out.println(ans);
out.close();
}
}