-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIndices.java
More file actions
61 lines (51 loc) · 1.65 KB
/
Indices.java
File metadata and controls
61 lines (51 loc) · 1.65 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
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Scanner;
public class Indices {
private static void fakeInput() {
String input = "6\n" +
"1 2 3 5 7 1";
System.setIn(new ByteArrayInputStream(input.getBytes()));
}
public static void main(String[] args) {
//fakeInput();
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] numbers = new int[n];
for (int i = 0; i < n; i++) {
numbers[i] = in.nextInt();
}
boolean[] used = new boolean[n];
for (int i = 0; i < n; i++) {
used[i] = false;
}
ArrayList<Integer> result = new ArrayList();
int cycleStartIndex = -1;
int currentIndex = 0;
while (-1 < currentIndex && currentIndex < n) {
if (used[currentIndex]) {
cycleStartIndex = currentIndex;
break;
}
used[currentIndex] = true;
result.add(currentIndex);
currentIndex = numbers[currentIndex];
}
StringBuilder output = new StringBuilder();
for (int x : result) {
if (x == cycleStartIndex) {
output.append("(");
}
output.append(x);
output.append(" ");
}
if(cycleStartIndex!=-1) {
output.append(")");
}
String outputString = output.toString();
outputString = outputString.replace(" (", "(");
outputString = outputString.replace(" )", ")");
outputString = outputString.trim();
System.out.println(outputString);
}
}