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)

#![allow(unused_imports)]
#![allow(non_snake_case, unused)]

use std::cmp::*;
use std::collections::*;
use std::ops::*;

macro_rules! eprint {
	($($t:tt)*) => {{
		use ::std::io::Write;
		let _ = write!(::std::io::stderr(), $($t)*);
	}};
}
macro_rules! eprintln {
	() => { eprintln!(""); };
	($($t:tt)*) => {{
		use ::std::io::Write;
		let _ = writeln!(::std::io::stderr(), $($t)*);
	}};
}
macro_rules! dbg {
	($v:expr) => {{
		let val = $v;
		eprintln!("[{}:{}] {} = {:?}", file!(), line!(), stringify!($v), val);
		val
	}}
}

macro_rules! mat {
	($($e:expr),*) => { Vec::from(vec![$($e),*]) };
	($($e:expr,)*) => { Vec::from(vec![$($e),*]) };
	($e:expr; $d:expr) => { Vec::from(vec![$e; $d]) };
	($e:expr; $d:expr $(; $ds:expr)+) => { Vec::from(vec![mat![$e $(; $ds)*]; $d]) };
}

macro_rules! ok {
	($a:ident$([$i:expr])*.$f:ident()$(@$t:ident)*) => {
		$a$([$i])*.$f($($t),*)
	};
	($a:ident$([$i:expr])*.$f:ident($e:expr$(,$es:expr)*)$(@$t:ident)*) => { {
		let t = $e;
		ok!($a$([$i])*.$f($($es),*)$(@$t)*@t)
	} };
}

pub fn readln() -> String {
	let mut line = String::new();
	::std::io::stdin().read_line(&mut line).unwrap_or_else(|e| panic!("{}", e));
	line
}

macro_rules! read {
	($($t:tt),*; $n:expr) => {{
		let stdin = ::std::io::stdin();
		let ret = ::std::io::BufRead::lines(stdin.lock()).take($n).map(|line| {
			let line = line.unwrap();
			let mut it = line.split_whitespace();
			_read!(it; $($t),*)
		}).collect::<Vec<_>>();
		ret
	}};
	($($t:tt),*) => {{
		let line = readln();
		let mut it = line.split_whitespace();
		_read!(it; $($t),*)
	}};
}

macro_rules! _read {
	($it:ident; [char]) => {
		_read!($it; String).chars().collect::<Vec<_>>()
	};
	($it:ident; [u8]) => {
		Vec::from(_read!($it; String).into_bytes())
	};
	($it:ident; usize1) => {
		$it.next().unwrap_or_else(|| panic!("input mismatch")).parse::<usize>().unwrap_or_else(|e| panic!("{}", e)) - 1
	};
	($it:ident; [usize1]) => {
		$it.map(|s| s.parse::<usize>().unwrap_or_else(|e| panic!("{}", e)) - 1).collect::<Vec<_>>()
	};
	($it:ident; [$t:ty]) => {
		$it.map(|s| s.parse::<$t>().unwrap_or_else(|e| panic!("{}", e))).collect::<Vec<_>>()
	};
	($it:ident; $t:ty) => {
		$it.next().unwrap_or_else(|| panic!("input mismatch")).parse::<$t>().unwrap_or_else(|e| panic!("{}", e))
	};
	($it:ident; $($t:tt),+) => {
		($(_read!($it; $t)),*)
	};
}

pub fn main() {
	let _ = ::std::thread::Builder::new().name("run".to_string()).stack_size(32 * 1024 * 1024).spawn(run).unwrap().join();
}

const MOD: usize = 1_000_000_007;
const INF: i64 = std::i64::MAX;

pub trait SetMinMax {
	fn setmin(&mut self, v: Self) -> bool;
	fn setmax(&mut self, v: Self) -> bool;
}
impl<T> SetMinMax for T where T: PartialOrd {
	fn setmin(&mut self, v: T) -> bool {
		*self > v && { *self = v; true }
	}
	fn setmax(&mut self, v: T) -> bool {
		*self < v && { *self = v; true }
	}
}

#[derive(Eq, PartialEq, Clone, Debug)]
pub struct Rev<T>(pub T);

impl<T: PartialOrd> PartialOrd for Rev<T> {
    fn partial_cmp(&self, other: &Rev<T>) -> Option<Ordering> {
        other.0.partial_cmp(&self.0)
    }
}

impl<T: Ord> Ord for Rev<T> {
    fn cmp(&self, other: &Rev<T>) -> Ordering {
        other.0.cmp(&self.0)
    }
}

fn solve() {
	let n = read!(usize);
	let a_tmp = read!([usize]);
	let mut a: Vec<usize> = a_tmp.iter().map(|x| x-1).collect();
	let mut res = vec![0;n];
	for i in 0..n {
		res[a[i]] += 1;
	}

	let mut ans = vec![];
	let mut set = BTreeSet::new();
	for i in 0..n {
		set.insert(i);
	}
	let mut prev = n;
	while set.len()>4 {
		let mut val = n;
		{
			let mut it = set.iter();
			val = it.next().unwrap().clone();
			if val==prev {
				val = it.next().unwrap().clone();
			}
		}
		let k = set.len();
		let y = a[val];
		if set.contains(&y) && k-1==res[y] {val=y;}
		ans.push(val);
		res[a[val]] -= 1;
		prev = a[val];
		set.remove(&val);
	}
	let mut v = vec![];
	for &i in set.iter(){
		v.push(i);
	}
	
	let mut ret = vec![];
	let mut p = vec![];
	let mut seen = vec![false;v.len()];
	search(&v,seen,&a,&mut ret,prev,p,n);
	ret.sort();

	if ret.len()==0 {
		println!("-1");
		return;
	}
	for &i in &ans {
		print!("{} ", i+1);
	}
	if v.len()==2 {
		print!("{} {}", ret[0].0, ret[0].1);
	}
	if v.len()==3 {
		print!("{} {} {}", ret[0].0, ret[0].1, ret[0].2);
	}
	if v.len()==4 {
		print!("{} {} {} {}", ret[0].0, ret[0].1, ret[0].2, ret[0].3);
	}
}

fn search(v: &Vec<usize>, mut seen: Vec<bool>, a: &[usize], mut ans: &mut Vec<(usize,usize,usize,usize)>, prev: usize, mut p: Vec<usize>, n: usize) {
	// println!("{} {} {}", v.len(), prev, p.len());
	if p.len()==v.len() {
		if p.len()==2 {ans.push((p[0],p[1],n,n));}
		if p.len()==3 {ans.push((p[0],p[1],p[2],n));}
		if p.len()==4 {ans.push((p[0],p[1],p[2],p[3]));}
		return;
	}
	for i in 0..v.len() {
		if seen[i] {continue;}
		let val = v[i];
		if val==prev {
			continue;
		}
		let mut seen_c = seen.clone();
		seen_c[i] = true;
		let mut p_c = p.clone();
		p_c.push(val+1);
		search(&v, seen_c, &a, &mut ans, a[val], p_c, n);
	}
}

fn run() {
    solve();
}