Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Indices {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- int num = Integer.parseInt(sc.nextLine());
- String[] str = sc.nextLine().split(" ");
- int[] arr = new int[num];
- boolean[]visited = new boolean[num];
- for (int i = 0; i<arr.length; i++) {
- arr[i] = Integer.parseInt(str[i]);
- }
- StringBuilder result = new StringBuilder();
- int currentIndex = 0;
- int loopStart = -1;
- while (true) {
- if (currentIndex<0|| currentIndex>=num) {
- break;
- }
- if (visited[currentIndex]) {
- loopStart = currentIndex;
- break;
- }
- result.append(currentIndex);
- result.append(" ");
- visited[currentIndex] = true;
- currentIndex = arr[currentIndex];
- }
- if (loopStart>=0) {
- int index =result.toString().indexOf(" "+loopStart+ " ");
- if (index<0) {
- result.insert(0,"(");
- } else {
- //result.indexOf(strr).append("(");
- result.setCharAt(index, '(');
- }
- //result.substring(result.length()-1);
- result.setCharAt(result.length()-1, ')');
- }
- System.out.println(result.toString().trim());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement