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: Accepted)

// ---------- begin SegmentTree Point update Range query ----------
mod segment_tree {
    pub struct PURQ<T: Clone, F: Fn(T, T) -> T> {
        n: usize,
        a: Vec<T>,
        id: T,
        op: F,
    }
    #[allow(dead_code)]
    impl<T: Clone, F: Fn(T, T) -> T> PURQ<T, F> {
        pub fn new(n: usize, id: T, op: F) -> PURQ<T, F> {
            let mut k = 1;
            while k < n {
                k *= 2;
            }
            PURQ {
                n: k,
                a: vec![id.clone(); 2 * k],
                id: id,
                op: op,
            }
        }
        pub fn update(&mut self, x: usize, v: T) {
            let mut k = self.n + x;
            let a = &mut self.a;
            a[k] = v;
            k >>= 1;
            while k > 0 {
                a[k] = (self.op)(a[2 * k].clone(), a[2 * k + 1].clone());
                k >>= 1;
            }
        }
        pub fn update_tmp(&mut self, x: usize, v: T) {
            self.a[x + self.n] = v;
        }
        pub fn update_all(&mut self) {
            for k in (1..(self.n)).rev() {
                self.a[k] = (self.op)(self.a[2 * k].clone(), self.a[2 * k + 1].clone());
            }
        }
        pub fn find(&self, mut l: usize, mut r: usize) -> T {
            let mut p = self.id.clone();
            let mut q = self.id.clone();
            l += self.n;
            r += self.n;
            while l < r {
                if (l & 1) == 1 {
                    p = (self.op)(p, self.a[l].clone());
                    l += 1;
                }
                if (r & 1) == 1 {
                    r -= 1;
                    q = (self.op)(self.a[r].clone(), q);
                }
                l >>= 1;
                r >>= 1;
            }
            (self.op)(p, q)
        }
    }
}
// ---------- end SegmentTree Point update Range query ----------
//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

fn valid(a: &[usize], ans: &[usize]) -> bool {
    for i in 1..ans.len() {
        if a[ans[i - 1]] == ans[i] {
            return false;
        }
    }
    true
}
 
fn dfs(ans: &mut [usize], a: &[usize], k: usize) -> bool {
    if k == 0 {
        return valid(a, ans);
    }
    if dfs(ans, a, k - 1) {
        return true;
    }
    let n = a.len() - 1;
    for i in (n - k + 1)..(n + 1) {
        ans.swap(n - k, i);
        if dfs(ans, a, k - 1) {
            return true;
        }
    }
    let t = ans[n - k];
    for i in (n - k + 1)..(n + 1) {
        ans[i - 1] = ans[i];
    }
    ans[n] = t;
    false
}

fn run() {
    input! {
        n: usize,
        a: [usize; n],
    }
    if n == 2 {
        println!("-1");
        return;
    }
    let mut seg = segment_tree::PURQ::new(n + 1, (0, 0), std::cmp::max);
    let mut deg = vec![0; n + 1];
    let mut a = a;
    a.insert(0, 0);
    for i in 1..(n + 1) {
        deg[a[i]] += 1;
    }
    for i in 1..(n + 1) {
        seg.update_tmp(i, (deg[i], i));
    }
    seg.update_all();
    let mut set: std::collections::BTreeSet<usize> = (1..(n + 1)).collect();
    let mut ans = vec![0; n + 1];
    for i in 1..(n + 1 - 3) {
        let (d, x) = seg.find(0, n + 1);
        let v = if d == n - i {
            x
        } else {
            let mut u = 0;
            for &k in set.iter() {
                if k != a[ans[i - 1]] {
                    u = k;
                    break;
                }
            }
            u
        };
        assert!(v != 0 && set.contains(&v));
        set.remove(&v);
        ans[i] = v;
        deg[a[v]] -= 1;
        seg.update(a[v], (deg[a[v]], a[v]));
        seg.update(v, (0, 0));
    }
    for ans in ans[(n - 2)..].iter_mut() {
        let v = *set.iter().next().unwrap();
        set.remove(&v);
        *ans = v;
    }
    assert!(set.is_empty());
    assert!(*ans.last().unwrap() != 0);
    dfs(&mut ans, &a, 2);
    let mut out = String::new();
    for a in ans[1..].iter() {
        out.push_str(&format!("{} ", *a));
    }
    out.pop();
    println!("{}", out);
}

fn main() {
    run();
}