#![allow(non_snake_case, unused_imports, unused_must_use)] use std::io::{self, prelude::*}; use std::str; fn main() { let (stdin, stdout) = (io::stdin(), io::stdout()); let mut scan = Scanner::new(stdin.lock()); let mut out = io::BufWriter::new(stdout.lock()); macro_rules! input { ($T: ty) => { scan.token::<$T>() }; ($T: ty, $N: expr) => { (0..$N).map(|_| scan.token::<$T>()).collect::>() }; } let N = input!(usize); let P = input!(usize, N); let mut pos_to_val = std::collections::BTreeMap::new(); for i in 0..N { pos_to_val.insert(i, P[i]); } let mut val_to_pos = std::collections::BTreeMap::new(); for i in 0..N { val_to_pos.insert(P[i], i); } let mut hq = std::collections::BinaryHeap::new(); for i in 0..N { hq.push(std::cmp::Reverse(P[i])); } let mut ans = vec![]; while !hq.is_empty() { let m = hq.pop().unwrap().0; match val_to_pos.get(&m) { Some(&p1) => { if p1 == N - 1 { continue; } match pos_to_val.range(p1 + 1..).next() { Some((&p2, &v2)) => { ans.push(m); ans.push(v2); pos_to_val.remove(&p1); pos_to_val.remove(&p2); val_to_pos.remove(&v2); val_to_pos.remove(&m); } None => { continue; } } } None => { continue; } } } writeln!( out, "{}", ans.iter() .map(|x| x.to_string()) .collect::>() .join(" ") ); } struct Scanner { reader: R, buf_str: Vec, buf_iter: str::SplitWhitespace<'static>, } impl Scanner { fn new(reader: R) -> Self { Self { reader, buf_str: vec![], buf_iter: "".split_whitespace(), } } fn token(&mut self) -> T { loop { if let Some(token) = self.buf_iter.next() { return token.parse().ok().expect("Failed parse"); } self.buf_str.clear(); self.reader .read_until(b'\n', &mut self.buf_str) .expect("Failed read"); self.buf_iter = unsafe { let slice = str::from_utf8_unchecked(&self.buf_str); std::mem::transmute(slice.split_whitespace()) } } } }