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::DisjointSparseTable;
  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_st = DisjointSparseTable::<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_st = DisjointSparseTable::<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_st.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_st } else { &odd_st }.concat(l..r);
    let min_x_i = p_i_map[min_x as usize];
    let min_y = if l % 2 == 0 { &odd_st } else { &even_st }.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_st } else { &odd_st }.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_st } else { &even_st }.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_st } else { &odd_st }.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::disjoint_sparse_table::*;

  mod disjoint_sparse_table {
    use math::algebra::Semigroup;
    use std::iter::FromIterator;
    use std::mem::size_of;
    use std::ops::Range;

    pub struct DisjointSparseTable<SG: Semigroup> {
      vecs: Vec<Vec<SG::T>>,
    }

    impl<SG: Semigroup> DisjointSparseTable<SG> {
      pub fn len(&self) -> usize {
        self.vecs[0].len()
      }

      pub fn concat(&self, range: Range<usize>) -> SG::T {
        assert!(range.start < range.end);
        assert!(range.end <= self.len());
        if range.start == range.end - 1 {
          return self.vecs[0][range.start].clone();
        }
        let row_index = size_of::<usize>() * 8 - (range.start ^ range.end - 1).leading_zeros() as usize - 1;
        SG::append(&self.vecs[row_index][range.start], &self.vecs[row_index][range.end - 1])
      }
    }

    impl<SG: Semigroup> FromIterator<SG::T> for DisjointSparseTable<SG> {
      fn from_iter<I: IntoIterator<Item = SG::T>>(iter: I) -> Self {
        let base = iter.into_iter().collect::<Vec<_>>();
        let len = base.len();
        let size = len.next_power_of_two();
        if size < 2 {
          return DisjointSparseTable { vecs: vec![base] };
        }
        let mut vecs = Vec::with_capacity(size.trailing_zeros() as usize);
        vecs.push(base);
        let mut r_width = 2usize;
        while r_width < len {
          let mut vec = Vec::with_capacity(len);
          unsafe {
            vec.set_len(len);
          }
          let mut r_mid = r_width;
          while r_mid - r_width < len {
            let (l_mid, l_width) = if r_mid < len {
              vec[r_mid] = vecs[0][r_mid].clone();
              for i in (r_mid + 1..r_mid + r_width).take_while(|i| *i < len) {
                vec[i] = SG::append(&vec[i - 1], &vecs[0][i]);
              }
              (r_mid - 1, r_width)
            } else {
              (len - 1, r_width - (r_mid - len))
            };
            vec[l_mid] = vecs[0][l_mid].clone();
            for i in (l_mid + 1 - l_width..l_mid).rev() {
              vec[i] = SG::append(&vecs[0][i], &vec[i + 1]);
            }
            r_mid += r_width * 2;
          }
          vecs.push(vec);
          r_width *= 2;
        }
        debug_assert_eq!(vecs.len(), size.trailing_zeros() as usize);
        DisjointSparseTable { vecs: vecs }
      }
    }
  }
}

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 }
  }
}