Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4.  
  5. public class Indices {
  6. public static void main(String[] args) throws IOException {
  7. BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
  8.  
  9. int gray = Integer.parseInt(bf.readLine());
  10.  
  11. String[] input = bf.readLine().split(" ");
  12. int[] arr = new int[input.length];
  13. StringBuilder raw = new StringBuilder("0");
  14.  
  15. for (int i = 0; i < input.length; i++) {
  16. arr[i] = Integer.parseInt(input[i]);
  17. }
  18. boolean[] visited = new boolean[input.length];
  19. visited[0] = true;
  20. int current = 0;
  21. int next;
  22. String output = "";
  23.  
  24.  
  25. while (true) {
  26.  
  27. next = arr[current];
  28.  
  29. if (next > input.length - 1 || next < 0) {
  30. output = raw.toString();
  31. break;
  32. }
  33.  
  34. if (!visited[next]) {
  35. visited[next] = true;
  36. raw.append(" ").append(next);
  37.  
  38. } else {
  39. raw.append(")");
  40. if (next == current && current == 0) {
  41. output = "(0)";
  42. } else if (next == 0) {
  43. output = "(" + raw.toString();
  44. } else if (next == current) {
  45. String temp = " " + current + ")";
  46. String replacement = "(" + current + ")";
  47. output = raw.toString().replace(temp, replacement);
  48. } else {
  49. String temp = " " + next + " ";
  50. String replacement = "(" + next + " ";
  51. output = raw.toString().replace(temp, replacement);
  52. }
  53. break;
  54. }
  55. current = next;
  56. }
  57. System.out.print(output);
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement