SlavCodes

Indices

Sep 8th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. import java.util.*;
  2. public class Test3 {
  3.  
  4.  
  5. public static void main(String[] args) {
  6. Scanner reader = new Scanner(System.in);
  7. int n = Integer.parseInt(reader.nextLine());
  8. String[] ARR = reader.nextLine().split(" ");
  9. StringBuffer myList = new StringBuffer();
  10. int currentIndex=0;
  11. boolean[] checked = new boolean[n];
  12. int loopSt=-1;
  13. while(true){
  14.  
  15. if(currentIndex<0||currentIndex>=n){
  16. break;
  17. }
  18. if(checked[currentIndex]){
  19. loopSt = currentIndex;
  20. break;
  21. }
  22.  
  23. myList.append(currentIndex);
  24. myList.append(" ");
  25. checked[currentIndex]=true;
  26. currentIndex = Integer.parseInt(ARR[currentIndex]);
  27. }
  28. if(loopSt>=0){
  29. int indexOfOccurance = myList.indexOf((" " + loopSt +" "));
  30.  
  31. if(indexOfOccurance<0){
  32. myList.insert(0,"(");
  33. } else {
  34. myList.setCharAt(indexOfOccurance,'(');
  35. }
  36. myList.setCharAt(myList.length()-1,')');
  37. }
  38. System.out.println(myList.toString().trim());
  39. }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment