Problem:
Score : 800 points

Problem Statement

Niwango has N cards, numbered 1,2,\ldots,N.
He will now arrange these cards in a row.

Niwango wants to know if there is a way to arrange the cards while satisfying all the N conditions below.
To help him, determine whether such a way exists. If the answer is yes, also find the lexicographically smallest such arrangement.

To the immediate right of Card 1 (if any) is NOT Card a_1.

To the immediate right of Card 2 (if any) is NOT Card a_2.

\vdots

To the immediate right of Card N (if any) is NOT Card a_N.

Constraints

2 \leq N \leq 10^{5}

1 \leq a_i \leq N

a_i \neq i

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

If no arrangements satisfy the conditions, print -1. If such arrangements exist, print the lexicographically smallest such arrangement, in the following format:

b_1 b_2 \ldots b_N

Here, b_i represents the i-th card from the left.

Sample Input 1

4
2 3 4 1

Sample Output 1

1 3 2 4

The arrangement (1,2,3,4) is lexicographically smaller than (1,3,2,4), but is invalid, since it violates the condition "to the immediate right of Card 1 is not Card 2."

Sample Input 2

2
2 1

Sample Output 2

-1

If no arrangements satisfy the conditions, print -1.

Sample Input 3

13
2 3 4 5 6 7 8 9 10 11 12 13 12

Sample Output 3

1 3 2 4 6 5 7 9 8 10 12 11 13

Solution in Rust (1.15.1) (judge verdict: Wrong Answer)

use std::collections::BinaryHeap;

fn main() {
    let (r, w) = (std::io::stdin(), std::io::stdout());
    let mut sc = IO::new(r.lock(), w.lock());

    let n: usize = sc.read();

    let a: Vec<usize> = (0..n).map(|_| sc.read::<usize>() - 1).collect();
    let mut ban_count = vec![0; n];
    for i in 0..n {
        ban_count[a[i]] += 1;
    }

    let mut ban_count_q = BinaryHeap::new();
    for i in 0..n {
        ban_count_q.push((ban_count[i], i));
    }
    let mut remain_q = BinaryHeap::new();
    for i in 0..n {
        remain_q.push(-(i as i64));
    }

    let mut used = vec![false; n];
    let mut ans = vec![];
    for _ in 0..n {
        let remain_size = remain_q.len();
        let mut candidate = vec![];
        while let Some((cur, i)) = ban_count_q.pop() {
            if used[i] {
            } else if cur != ban_count[i] {
                ban_count_q.push((ban_count[i], i));
            } else if ban_count[i] + 1 == remain_size {
                candidate.push(i);
            } else {
                assert!(ban_count[i] + 1 < remain_size);
                ban_count_q.push((ban_count[i], i));
                break;
            }
        }
        if candidate.len() > 1 {
            println!("-1");
            return;
        }
        if candidate.is_empty() {
            let first = pop(&mut remain_q, &used);
            let can_select_first = ans.is_empty() || a[ans[ans.len() - 1]] != first;
            if can_select_first {
                ans.push(first);
                used[first] = true;
                ban_count[a[first]] -= 1;
            } else {
                let second = pop(&mut remain_q, &used);
                ans.push(second);
                used[second] = true;
                ban_count[a[second]] -= 1;
                remain_q.push(-(first as i64));
            }
        } else {
            let select = candidate[0];
            ans.push(select);
            used[select] = true;
            ban_count[a[select]] -= 1;
        }
    }

    for i in 1..n {
        assert_ne!(a[ans[i - 1]], ans[i]);
    }

    for i in 0..n {
        if i > 0 {
            sc.write(" ");
        }
        sc.write(format!("{}", ans[i] + 1));
    }
    sc.write("\n");
}

fn pop(q: &mut BinaryHeap<i64>, used: &Vec<bool>) -> usize {
    while let Some(x) = q.pop() {
        let i = (-x) as usize;
        if !used[i] {
            return i;
        }
    }
    unreachable!()
}

pub struct IO<R, W: std::io::Write>(R, std::io::BufWriter<W>);

impl<R: std::io::Read, W: std::io::Write> IO<R, W> {
    pub fn new(r: R, w: W) -> IO<R, W> {
        IO(r, std::io::BufWriter::new(w))
    }
    pub fn write<S: std::ops::Deref<Target = str>>(&mut self, s: S) {
        use std::io::Write;
        self.1.write(s.as_bytes()).unwrap();
    }
    pub fn read<T: std::str::FromStr>(&mut self) -> T {
        use std::io::Read;
        let buf = self
            .0
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b' ' || b == b'\n' || b == b'\r' || b == b'\t')
            .take_while(|&b| b != b' ' && b != b'\n' && b != b'\r' && b != b'\t')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read()).collect()
    }
    pub fn chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
}