Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class Test3 {
- public static void main(String[] args) {
- Scanner reader = new Scanner(System.in);
- int n = Integer.parseInt(reader.nextLine());
- String[] ARR = reader.nextLine().split(" ");
- StringBuffer myList = new StringBuffer();
- int currentIndex=0;
- boolean[] checked = new boolean[n];
- int loopSt=-1;
- while(true){
- if(currentIndex<0||currentIndex>=n){
- break;
- }
- if(checked[currentIndex]){
- loopSt = currentIndex;
- break;
- }
- myList.append(currentIndex);
- myList.append(" ");
- checked[currentIndex]=true;
- currentIndex = Integer.parseInt(ARR[currentIndex]);
- }
- if(loopSt>=0){
- int indexOfOccurance = myList.indexOf((" " + loopSt +" "));
- if(indexOfOccurance<0){
- myList.insert(0,"(");
- } else {
- myList.setCharAt(indexOfOccurance,'(');
- }
- myList.setCharAt(myList.length()-1,')');
- }
- System.out.println(myList.toString().trim());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment