Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- public class Indices {
- public static void main(String[] args) throws IOException {
- BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
- int gray = Integer.parseInt(bf.readLine());
- String[] input = bf.readLine().split(" ");
- int[] arr = new int[input.length];
- StringBuilder raw = new StringBuilder("0");
- for (int i = 0; i < input.length; i++) {
- arr[i] = Integer.parseInt(input[i]);
- }
- boolean[] visited = new boolean[input.length];
- visited[0] = true;
- int current = 0;
- int next;
- String output = "";
- while (true) {
- next = arr[current];
- if (next > input.length - 1 || next < 0) {
- output = raw.toString();
- break;
- }
- if (!visited[next]) {
- visited[next] = true;
- raw.append(" ").append(next);
- } else {
- raw.append(")");
- if (next == current && current == 0) {
- output = "(0)";
- } else if (next == 0) {
- output = "(" + raw.toString();
- } else if (next == current) {
- String temp = " " + current + ")";
- String replacement = "(" + current + ")";
- output = raw.toString().replace(temp, replacement);
- } else {
- String temp = " " + next + " ";
- String replacement = "(" + next + " ";
- output = raw.toString().replace(temp, replacement);
- }
- break;
- }
- current = next;
- }
- System.out.print(output);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement