Advertisement
fit_max

Indices

Dec 6th, 2019
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Indices {
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6. int num = Integer.parseInt(sc.nextLine());
  7. String[] str = sc.nextLine().split(" ");
  8. int[] arr = new int[num];
  9. boolean[]visited = new boolean[num];
  10. for (int i = 0; i<arr.length; i++) {
  11. arr[i] = Integer.parseInt(str[i]);
  12. }
  13. StringBuilder result = new StringBuilder();
  14. int currentIndex = 0;
  15. int loopStart = -1;
  16. while (true) {
  17. if (currentIndex<0|| currentIndex>=num) {
  18. break;
  19. }
  20. if (visited[currentIndex]) {
  21. loopStart = currentIndex;
  22. break;
  23. }
  24. result.append(currentIndex);
  25. result.append(" ");
  26. visited[currentIndex] = true;
  27. currentIndex = arr[currentIndex];
  28. }
  29. if (loopStart>=0) {
  30. int index =result.toString().indexOf(" "+loopStart+ " ");
  31. if (index<0) {
  32. result.insert(0,"(");
  33.  
  34. } else {
  35. //result.indexOf(strr).append("(");
  36. result.setCharAt(index, '(');
  37. }
  38. //result.substring(result.length()-1);
  39. result.setCharAt(result.length()-1, ')');
  40.  
  41. }
  42. System.out.println(result.toString().trim());
  43. }
  44.  
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement