-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBovineShuffle.java
More file actions
56 lines (56 loc) · 1.34 KB
/
BovineShuffle.java
File metadata and controls
56 lines (56 loc) · 1.34 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
import java.io.*;
import java.util.*;
public class BovineShuffle {
public static void main(String[] args) throws IOException, InterruptedException
{
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader br = new BufferedReader(new FileReader("shuffle.in"));
int num = Integer.parseInt(br.readLine());
String[] temp = br.readLine().split(" ");
int[] outGoing = new int[num+1];
for (int i = 1; i < num+1; i++)
outGoing[i] = Integer.parseInt(temp[i-1]);
boolean[] checked = new boolean[num+1];
boolean[] path = new boolean[num+1];
int j;
int count = 0;
int pivot;
boolean isSolution;
for (int i = 1; i < num + 1; i++)
{
if (checked[i])
continue;
j = i;
isSolution = true;
while(!path[j])
{
if (checked[j] && !path[j])
{
isSolution = false;
break;
}
path[j] = true;
checked[j] = true;
j = outGoing[j];
}
Arrays.fill(path, false);
if (!isSolution)
continue;
pivot = j;
count++;
while(outGoing[j]!=pivot)//infinite loop
{
count++;
j = outGoing[j];
//for (boolean el: path)
// System.out.print(el + " ");
//System.out.println();
}
}
//System.out.println(count);
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("shuffle.out")));
pw.println(count);
pw.close();
br.close();
}
}