Problem:
Score : 800 points

Problem Statement

Let N be a positive even number.

We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N).
Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.

First, let q be an empty sequence.
Then, perform the following operation until p becomes empty:

Select two adjacent elements in p, and call them x and y in order. Remove x and y from p (reducing the length of p by 2), and insert x and y, preserving the original order, at the beginning of q.

When p becomes empty, q will be a permutation of (1, 2, ..., N).

Find the lexicographically smallest permutation that can be obtained as q.

Constraints

N is an even number.

2 ≤ N ≤ 2 × 10^5

p is a permutation of (1, 2, ..., N).

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 ... p_N

Output

Print the lexicographically smallest permutation, with spaces in between.

Sample Input 1

4
3 2 4 1

Sample Output 1

3 1 2 4

The solution above is obtained as follows:

p

q

(3, 2, 4, 1)

()

↓

↓

(3, 1)

(2, 4)

↓

↓

()

(3, 1, 2, 4)

Sample Input 2

2
1 2

Sample Output 2

1 2

Sample Input 3

8
4 6 3 2 8 5 7 1

Sample Output 3

3 1 2 7 4 6 8 5

The solution above is obtained as follows:

p

q

(4, 6, 3, 2, 8, 5, 7, 1)

()

↓

↓

(4, 6, 3, 2, 7, 1)

(8, 5)

↓

↓

(3, 2, 7, 1)

(4, 6, 8, 5)

↓

↓

(3, 1)

(2, 7, 4, 6, 8, 5)

↓

↓

()

(3, 1, 2, 7, 4, 6, 8, 5)

Solution in Rust (1.15.1) (judge verdict: Accepted)

macro_rules! semigroup_impl {
  ($marker:ty, $t:ty, | $lhs:ident, $rhs:ident | $append:expr) => {
    impl $crate::math::algebra::Semigroup for $marker {
      type T = $t;

      fn append($lhs: &$t, $rhs: &$t) -> $t {
        $append
      }
    }
  };
}

macro_rules! monoid_impl {
  ($marker:ty, $t:ty, | $lhs:ident, $rhs:ident | $append:expr, $identity:expr) => {
    semigroup_impl! { $marker, $t, |$lhs, $rhs| $append }

    impl $crate::math::algebra::Monoid for $marker {
      fn identity() -> $t {
        $identity
      }
    }
  };
}

macro_rules! commutative_monoid_impl {
  ($marker:ty, $t:ty, | $lhs:ident, $rhs:ident | $append:expr, $identity:expr) => {
    monoid_impl! { $marker, $t, |$lhs, $rhs| $append, $identity }

    impl $crate::math::algebra::CommutativeMonoid for $marker {}
  };
}

fn solve<R: BufRead, W: Write>(_reader: R, _writer: &mut W) {
  let mut _scanner = Scanner::new(_reader);

  #[allow(unused_macros)]
  macro_rules! scan {
    ($t:ty) => {
      _scanner.next::<$t>().unwrap()
    };
    ($($t:ty),+) => {
      ($(scan!($t)),+)
    };
    ($t:ty; $n:expr) => {
      scan_iter!($t; $n).collect::<Vec<_>>()
    };
    ($t_0:ty, $t_1:ty; $n:expr) => {
      scan!($t_0 = 0, $t_1 = 1; $n)
    };
    ($t_0:ty, $t_1:ty, $t_2:ty; $n:expr) => {
      scan!($t_0 = 0, $t_1 = 1, $t_2 = 2; $n)
    };
    ($($t:ty = $i:tt),+; $n:expr) => {{
      let mut vecs = ($(Vec::<$t>::with_capacity($n)),+);
      for _ in 0..$n {$(
        vecs.$i.push(scan!($t));
      )+}
      vecs
    }};
  }

  #[allow(unused_macros)]
  macro_rules! scan_iter {
    ($t:ty; $n:expr) => {
      _scanner.take::<$t>($n).map(|x| x.unwrap())
    };
  }

  #[allow(unused_macros)]
  macro_rules! print {
    ($fmt:expr) => {
      write!(_writer, $fmt).unwrap()
    };
    ($fmt:expr, $($arg:tt)*) => {
      write!(_writer, $fmt, $($arg)*).unwrap()
    };
  }

  #[allow(unused_macros)]
  macro_rules! println {
    () => {
      writeln!(_writer).unwrap()
    };
    ($fmt:expr) => {
      writeln!(_writer, $fmt).unwrap()
    };
    ($fmt:expr, $($arg:tt)*) => {
      writeln!(_writer, $fmt, $($arg)*).unwrap()
    };
  }

  use data_structures::SegmentTree;
  use math::algebra::MinMonoid;
  use std::collections::BinaryHeap;
  use std::iter::FromIterator;

  let n = scan!(usize);
  let p = scan!(i64; n);
  let mut p_i_map = vec![0; n + 1];
  for (i, p_i) in p.iter().cloned().enumerate() {
    p_i_map[p_i as usize] = i;
  }

  let even_p_iter = p.iter().cloned().enumerate().map(|(i, x)| if i % 2 == 0 { x } else { i64::max_value() });
  let even_segtree = SegmentTree::<MinMonoid<i64>>::from_iter(even_p_iter);
  let odd_p_iter = p.iter().cloned().enumerate().map(|(i, x)| if i % 2 != 0 { x } else { i64::max_value() });
  let odd_segtree = SegmentTree::<MinMonoid<i64>>::from_iter(odd_p_iter);

  let min_x_i = 0usize;
  let min_y_i = n;
  let mut pq = BinaryHeap::new();
  pq.push((-even_segtree.concat(min_x_i..min_y_i), min_x_i, min_y_i));

  while let Some((_, l, r)) = pq.pop() {
    let min_x = if l % 2 == 0 { &even_segtree } else { &odd_segtree }.concat(l..r);
    let min_x_i = p_i_map[min_x as usize];
    let min_y = if l % 2 == 0 { &odd_segtree } else { &even_segtree }.concat(min_x_i + 1..r);
    let min_y_i = p_i_map[min_y as usize];

    print!("{} {} ", min_x, min_y);

    {
      let new_r = min_x_i;
      if (l..new_r).len() > 0 {
        let min = if l % 2 == 0 { &even_segtree } else { &odd_segtree }.concat(l..new_r);
        pq.push((-min, l, new_r));
      }
    }
    {
      let new_l = min_x_i + 1;
      let new_r = min_y_i;
      if (new_l..new_r).len() > 0 {
        let min = if l % 2 == 0 { &odd_segtree } else { &even_segtree }.concat(new_l..new_r);
        pq.push((-min, new_l, new_r));
      }
    }
    {
      let new_l = min_y_i + 1;
      if (new_l..r).len() > 0 {
        let min = if l % 2 == 0 { &even_segtree } else { &odd_segtree }.concat(new_l..r);
        pq.push((-min, new_l, r));
      }
    }
  }
}

fn main() {
  let stdin = stdin();
  let stdout = stdout();
  #[cfg(debug_assertions)]
  let mut writer = stdout.lock();
  #[cfg(not(debug_assertions))]
  let mut writer = ::std::io::BufWriter::new(stdout.lock());
  solve(stdin.lock(), &mut writer);
  writer.flush().unwrap();
}

use io::Scanner;
use std::io::{stdin, stdout, BufRead, Write};

pub mod math {
  pub mod algebra {
    pub use self::commutative_monoid::*;
    pub use self::min_monoid::*;
    pub use self::monoid::*;
    pub use self::semigroup::*;

    mod semigroup {
      use std::fmt::Debug;

      pub trait Semigroup {
        type T: Clone + PartialEq + Debug;

        fn append(lhs: &Self::T, rhs: &Self::T) -> Self::T;

        fn append_assign(lhs: &mut Self::T, rhs: &Self::T) {
          *lhs = Self::append(lhs, rhs);
        }
      }
    }

    mod monoid {
      use math::algebra::Semigroup;

      pub trait Monoid: Semigroup {
        fn identity() -> Self::T;
      }
    }

    mod commutative_monoid {
      use math::algebra::Monoid;

      pub trait CommutativeMonoid: Monoid {}
    }

    mod min_monoid {
      use std::cmp::min;
      use std::marker::PhantomData;

      pub struct MinMonoid<T: Ord> {
        _marker: PhantomData<fn() -> T>,
      }

      macro_rules! min_monoid_impl {
        ($($t:ident)+) => {$(
          commutative_monoid_impl! { MinMonoid<$t>, $t, |lhs, rhs| min(*lhs, *rhs), $t::max_value() }
        )+};
      }

      min_monoid_impl! { i32 i64 isize u8 u32 u64 usize }
    }
  }
}

pub mod data_structures {
  pub use self::segment_tree::*;

  mod segment_tree {
    use math::algebra::Monoid;
    use std::iter::FromIterator;
    use std::ops::{Index, Range};

    pub struct SegmentTree<M: Monoid> {
      vec: Vec<M::T>,
      len: usize,
    }

    impl<M: Monoid> SegmentTree<M> {
      pub fn new(size: usize) -> Self {
        let len = size;
        let size = size.checked_next_power_of_two().unwrap();
        SegmentTree {
          vec: vec![M::identity(); size.checked_mul(2).unwrap()],
          len: len,
        }
      }

      pub fn len(&self) -> usize {
        self.len
      }

      fn size(&self) -> usize {
        self.vec.len() / 2
      }

      pub fn get(&mut self, index: usize) -> M::T {
        debug_assert!(index < self.len());
        self[index].clone()
      }

      pub fn set(&mut self, index: usize, x: &M::T) {
        assert!(index < self.len());
        let mut i = index + self.size();
        self.vec[i] = x.clone();
        i /= 2;
        while i > 0 {
          self.vec[i] = M::append(&self.vec[i * 2], &self.vec[i * 2 + 1]);
          i /= 2;
        }
      }

      pub fn concat(&self, range: Range<usize>) -> M::T {
        assert!(range.start <= range.end);
        assert!(range.end <= self.len());
        let mut lacc = M::identity();
        let mut racc = M::identity();
        let mut l = range.start + self.size();
        let mut r = range.end + self.size();
        while l < r {
          if l % 2 != 0 {
            lacc = M::append(&lacc, &self.vec[l]);
            l += 1;
          }
          if r % 2 != 0 {
            r -= 1;
            racc = M::append(&self.vec[r], &racc);
          }
          l /= 2;
          r /= 2;
        }
        M::append(&lacc, &racc)
      }
    }

    impl<M: Monoid> FromIterator<M::T> for SegmentTree<M> {
      fn from_iter<I: IntoIterator<Item = M::T>>(iter: I) -> Self {
        let iter = iter.into_iter();
        match iter.size_hint() {
          (lower_bound, Some(upper_bound)) if lower_bound == upper_bound => Self::from_exact_size_iter(upper_bound, iter),
          _ => {
            let vec = iter.collect::<Vec<_>>();
            Self::from_exact_size_iter(vec.len(), vec)
          }
        }
      }
    }

    impl<M: Monoid> SegmentTree<M> {
      fn from_exact_size_iter<I: IntoIterator<Item = M::T>>(len: usize, iter: I) -> Self {
        let iter = iter.into_iter();
        let size = len.checked_next_power_of_two().unwrap();
        let mut vec = Vec::with_capacity(size.checked_mul(2).unwrap());
        for _ in 0..size {
          vec.push(M::identity());
        }
        vec.extend(iter);
        for _ in 0..size - len {
          vec.push(M::identity());
        }
        for i in (1..size).rev() {
          vec[i] = M::append(&vec[i * 2], &vec[i * 2 + 1]);
        }
        SegmentTree { vec: vec, len: len }
      }
    }

    impl<M: Monoid> Index<usize> for SegmentTree<M> {
      type Output = M::T;

      fn index(&self, index: usize) -> &M::T {
        assert!(index < self.len());
        &self.vec[index + self.size()]
      }
    }
  }
}

pub mod io {
  pub use self::scanner::*;

  mod scanner {
    use std::io::BufRead;
    use std::marker::PhantomData;
    use std::str::{from_utf8, FromStr};

    pub struct Scanner<R> {
      reader: R,
      buffer: Vec<u8>,
      position: usize,
    }

    impl<R: BufRead> Scanner<R> {
      pub fn new(reader: R) -> Self {
        Scanner { reader: reader, buffer: vec![], position: 0 }
      }

      pub fn next<T: Parse>(&mut self) -> Option<T> {
        Parse::parse(self.next_bytes().unwrap_or(&[]))
      }

      pub fn take<T: Parse>(&mut self, n: usize) -> Take<R, T> {
        Take { scanner: self, n: n, _marker: PhantomData }
      }

      pub fn next_bytes(&mut self) -> Option<&[u8]> {
        if self.buffer.is_empty() {
          self.read_line();
        }
        loop {
          match self.buffer.get(self.position) {
            Some(&b' ') => self.position += 1,
            Some(&b'\n') => self.read_line(),
            Some(_) => break,
            None => return None,
          }
        }
        let start = self.position;
        loop {
          match self.buffer.get(self.position) {
            Some(&b' ') | Some(&b'\n') | None => break,
            Some(_) => self.position += 1,
          }
        }
        Some(&self.buffer[start..self.position])
      }

      fn read_line(&mut self) {
        self.position = 0;
        self.buffer.clear();
        self.reader.read_until(b'\n', &mut self.buffer).unwrap();
      }
    }

    pub struct Take<'a, R: 'a, T> {
      scanner: &'a mut Scanner<R>,
      n: usize,
      _marker: PhantomData<fn() -> T>,
    }

    impl<'a, R: BufRead, T: Parse> Iterator for Take<'a, R, T> {
      type Item = Option<T>;

      fn next(&mut self) -> Option<Self::Item> {
        if self.n > 0 {
          self.n -= 1;
          Some(self.scanner.next())
        } else {
          None
        }
      }

      fn size_hint(&self) -> (usize, Option<usize>) {
        (self.n, Some(self.n))
      }
    }

    impl<'a, R: BufRead, T: Parse> ExactSizeIterator for Take<'a, R, T> {}

    pub trait Parse: Sized {
      fn parse(bytes: &[u8]) -> Option<Self>;
    }

    impl Parse for u8 {
      fn parse(bytes: &[u8]) -> Option<Self> {
        if bytes.len() == 1 {
          Some(*unsafe { bytes.get_unchecked(0) })
        } else {
          None
        }
      }
    }

    macro_rules! parse_impl {
      ($($t:ident)+) => {$(
        impl Parse for $t {
          fn parse(bytes: &[u8]) -> Option<Self> {
            from_utf8(bytes).ok().and_then(|s| $t::from_str(s).ok())
          }
        }
      )+};
    }

    parse_impl! { i32 i64 u32 u64 isize usize String }
  }
}