macro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); let mut next = || { iter.next().unwrap() }; input_inner!{next, $($r)*} }; ($($r:tt)*) => { let stdin = std::io::stdin(); let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock())); let mut next = move || -> String{ bytes .by_ref() .map(|r|r.unwrap() as char) .skip_while(|c|c.is_whitespace()) .take_while(|c|!c.is_whitespace()) .collect() }; input_inner!{next, $($r)*} }; } macro_rules! input_inner { ($next:expr) => {}; ($next:expr, ) => {}; ($next:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($next, $t); input_inner!{$next $($r)*} }; } macro_rules! read_value { ($next:expr, ( $($t:tt),* )) => { ( $(read_value!($next, $t)),* ) }; ($next:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($next, $t)).collect::>() }; ($next:expr, Chars) => { read_value!($next, String).chars().collect::>() }; ($next:expr, Usize1) => { read_value!($next, usize) - 1 }; ($next:expr, $t:ty) => { $next().parse::<$t>().expect("Parse error") }; } fn main() { input! { n: usize, p: [Usize1; n], } let mut idx = vec![0; n]; for (i, &p) in p.iter().enumerate() { idx[p] = i; } let mut v = (0..n).collect::>(); let mut used = vec![false; n]; let mut ans = vec![]; for x in 0..n { let i = idx[x]; if i != v[i] || i == n - 1 { continue; } let j = if i + 1 != tail(v[i + 1], &mut v) { tail(v[i + 1], &mut v) + 1 } else { i + 1 }; if j == n { continue; } if used[i] || used[j] { continue; } if i > 0 && used[i - 1] { union(i, i - 1, &mut v); } if j < n - 1 && used[j + 1] { union(j, j + 1, &mut v); } union(i, i + 1, &mut v); union(j - 1, j, &mut v); used[i] = true; used[j] = true; ans.push(p[i]); ans.push(p[j]); } for (i, ans) in ans.iter().enumerate() { if i > 0 { print!(" "); } print!("{}", ans + 1); } println!(); } fn tail(x: usize, v: &mut Vec) -> usize { if x == v[x] { x } else { v[x] = tail(v[x], v); v[x] } } fn union(x: usize, y: usize, v: &mut Vec) { let tx = tail(x, v); let ty = tail(y, v); if tx < ty { v[tx] = ty; } else { v[ty] = tx; } }