fit_max

Untitled

Dec 5th, 2019
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 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 + " ").toString());
  31. if (index<0) {
  32. result.insert(0,"(");
  33. } else {
  34. result.append(")") ;
  35. }
  36. result.substring(result.length()-1);
  37.  
  38. }
  39. System.out.println(result.toString().trim());
  40. }
  41.  
  42. }
Add Comment
Please, Sign In to add comment