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 ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; input_inner ! { iter , $ ( $ r ) * } } ; ( iter = $ iter : ident , $ ( $ r : tt ) * ) => { let s = { use std :: io :: Read ; let mut s = String :: new ( ) ; std :: io :: stdin ( ) . read_to_string ( & mut s ) . unwrap ( ) ; s } ; let mut $ iter = s . split_whitespace ( ) ; input_inner ! { $ iter , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let s = { use std :: io :: Read ; let mut s = String :: new ( ) ; std :: io :: stdin ( ) . read_to_string ( & mut s ) . unwrap ( ) ; s } ; let mut iter = s . split_whitespace ( ) ; input_inner ! { iter , $ ( $ r ) * } } ; }
macro_rules ! input_inner { ( $ iter : expr ) => { } ; ( $ iter : expr , ) => { } ; ( $ iter : expr , mut $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let mut $ var = read_value ! ( $ iter , $ t ) ; input_inner ! { $ iter $ ( $ r ) * } } ; ( $ iter : expr , mut $ var : ident $ ( $ r : tt ) * ) => { input_inner ! { $ iter , mut $ var : usize $ ( $ r ) * } } ; ( $ iter : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ iter , $ t ) ; input_inner ! { $ iter $ ( $ r ) * } } ; ( $ iter : expr , $ var : ident $ ( $ r : tt ) * ) => { input_inner ! { $ iter , $ var : usize $ ( $ r ) * } } ; }
macro_rules ! read_value { ( $ iter : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ iter , $ t ) ) ,* ) } ; ( $ iter : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ iter , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ iter : expr , { chars : $ base : expr } ) => { read_value ! ( $ iter , String ) . chars ( ) . map ( | c | ( c as u8 - $ base as u8 ) as usize ) . collect ::< Vec < usize >> ( ) } ; ( $ iter : expr , { char : $ base : expr } ) => { read_value ! ( $ iter , { chars : $ base } ) [ 0 ] } ; ( $ iter : expr , chars ) => { read_value ! ( $ iter , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ iter : expr , char ) => { read_value ! ( $ iter , chars ) [ 0 ] } ; ( $ iter : expr , usize1 ) => { read_value ! ( $ iter , usize ) - 1 } ; ( $ iter : expr , $ t : ty ) => { $ iter . next ( ) . unwrap ( ) . parse ::<$ t > ( ) . unwrap ( ) } ; }
pub trait Monoid {
    type T: Clone + PartialEq;
    fn mempty(&self) -> Self::T;
    fn mappend(&self, x: &Self::T, y: &Self::T) -> Self::T;
}
#[derive(Clone, Debug)]
pub struct SegmentTree<M: Monoid> {
    pub n: usize,
    pub seg: Vec<M::T>,
    pub m: M,
}
impl<M: Monoid> SegmentTree<M> {
    pub fn new(n: usize, m: M) -> SegmentTree<M> {
        let n = 1 << format!("{:b}", n - 1).len();
        let seg = vec![m.mempty(); 2 * n - 1];
        SegmentTree {
            n: n,
            seg: seg,
            m: m,
        }
    }
    pub fn from_vec(v: Vec<M::T>, m: M) -> SegmentTree<M> {
        let n = 1 << format!("{:b}", v.len() - 1).len();
        let mut seg = vec![m.mempty(); 2 * n - 1];
        for (i, x) in v.into_iter().enumerate() {
            seg[i + n - 1] = x;
        }
        for i in (0..n - 1).rev() {
            seg[i] = m.mappend(&seg[2 * i + 1], &seg[2 * i + 2]);
        }
        SegmentTree {
            n: n,
            seg: seg,
            m: m,
        }
    }
    pub fn update(&mut self, k: usize, x: M::T) {
        let mut k = k + self.n - 1;
        self.seg[k] = x;
        while k > 0 {
            k = (k - 1) / 2;
            self.seg[k] = self.m.mappend(&self.seg[2 * k + 1], &self.seg[2 * k + 2]);
        }
    }
    pub fn query(&self, l: usize, r: usize) -> M::T {
        let mut l = l + self.n - 1;
        let mut r = r + self.n - 1;
        let mut vl = self.m.mempty();
        let mut vr = self.m.mempty();
        while l < r {
            if l & 1 == 0 {
                vl = self.m.mappend(&vl, &self.seg[l]);
                l += 1;
            }
            if r & 1 == 0 {
                r -= 1;
                vr = self.m.mappend(&self.seg[r], &vr);
            }
            l = (l - 1) / 2;
            r = (r - 1) / 2;
        }
        self.m.mappend(&vl, &vr)
    }
}
#[derive(Clone, Debug)]
pub struct AnyMonoid<T: Clone, F: Fn(&T, &T) -> T> {
    id: T,
    op: F,
}
impl<T: Clone, F: Fn(&T, &T) -> T> AnyMonoid<T, F> {
    pub fn new(id: T, op: F) -> AnyMonoid<T, F> {
        AnyMonoid { id: id, op: op }
    }
}
impl<T: Clone + PartialEq, F: Fn(&T, &T) -> T> Monoid for AnyMonoid<T, F> {
    type T = T;
    #[inline]
    fn mempty(&self) -> T {
        self.id.clone()
    }
    #[inline]
    fn mappend(&self, x: &T, y: &T) -> T {
        (self.op)(x, y)
    }
}
#[inline]
fn rmb(k: usize) -> usize {
    (k as isize & -(k as isize)) as usize
}
pub trait Group: Monoid {
    fn invert(&self, x: &Self::T) -> Self::T;
}
#[derive(Clone, Debug)]
pub struct BinaryIndexedTree<M: Monoid> {
    bit: Vec<M::T>,
    m: M,
}
impl<M: Monoid> BinaryIndexedTree<M> {
    pub fn new(n: usize, m: M) -> BinaryIndexedTree<M> {
        let bit = vec![m.mempty(); n + 1];
        BinaryIndexedTree { bit: bit, m: m }
    }
    #[doc = " 1-indexed"]
    pub fn query(&self, k: usize) -> M::T {
        let mut res = self.m.mempty();
        let mut k = k;
        while k > 0 {
            res = self.m.mappend(&res, &self.bit[k]);
            k -= rmb(k);
        }
        res
    }
    #[doc = " 1-indexed"]
    pub fn update(&mut self, k: usize, x: M::T) {
        let mut k = k;
        while k < self.bit.len() {
            self.bit[k] = self.m.mappend(&self.bit[k], &x);
            k += rmb(k);
        }
    }
}
impl<G: Group> BinaryIndexedTree<G> {
    #[doc = " 0-indexed [l, r)"]
    pub fn query_section(&self, l: usize, r: usize) -> G::T {
        self.m
            .mappend(&self.m.invert(&self.query(l)), &self.query(r))
    }
    #[doc = " 1-indexed"]
    pub fn get_val(&self, k: usize) -> G::T {
        self.query_section(k - 1, k)
    }
    #[doc = " 1-indexed"]
    pub fn set_val(&mut self, k: usize, x: G::T) {
        let y = self.m.invert(&self.get_val(k));
        let z = self.m.mappend(&y, &x);
        self.update(k, z);
    }
}
impl<M: Monoid> BinaryIndexedTree<M>
where
    M::T: Ord,
{
    #[doc = " 0-indexed"]
    pub fn lower_bound(&self, x: M::T) -> (usize, M::T) {
        let n = self.bit.len() - 1;
        let mut acc = self.m.mempty();
        let mut pos = 0;
        let mut k = 1 << format!("{:b}", n).len();
        while k > 0 {
            if k + pos <= n && self.m.mappend(&acc, &self.bit[k + pos]) < x {
                pos += k;
                acc = self.m.mappend(&acc, &self.bit[pos]);
            }
            k >>= 1;
        }
        (pos, acc)
    }
}
#[derive(Clone, Debug)]
pub struct AddGroup<T: Copy + std::ops::Add<Output = T> + std::ops::Neg<Output = T>> {
    zero: T,
}
impl<T: Copy + std::ops::Add<Output = T> + std::ops::Neg<Output = T>> AddGroup<T> {
    pub fn new(zero: T) -> AddGroup<T> {
        AddGroup { zero: zero }
    }
}
impl<T: Copy + std::ops::Add<Output = T> + std::ops::Neg<Output = T> + PartialEq> Monoid
    for AddGroup<T>
{
    type T = T;
    #[inline]
    fn mempty(&self) -> T {
        self.zero.clone()
    }
    #[inline]
    fn mappend(&self, x: &T, y: &T) -> T {
        *x + *y
    }
}
impl<T: Copy + std::ops::Add<Output = T> + std::ops::Neg<Output = T> + PartialEq> Group
    for AddGroup<T>
{
    fn invert(&self, x: &T) -> T {
        -*x
    }
}
use std::cmp::min;
fn main() {
    input! { n, p: [usize1; n] };
    const INF: usize = 1_001_001_001;
    let v = (0..n).map(|i| (1, p[i], INF)).collect::<Vec<_>>();
    let id = (0, INF, INF);
    let mut seg = SegmentTree::from_vec(
        v,
        AnyMonoid::new(id, |x, y| {
            if x.0 % 2 == 1 {
                (x.0 + y.0, min(x.1, y.2), min(x.2, y.1))
            } else {
                (x.0 + y.0, min(x.1, y.1), min(x.2, y.2))
            }
        }),
    );
    let mut bit = BinaryIndexedTree::new(n + 1, AddGroup::new(0i32));
    let mut c = vec![0; n];
    for i in 0..n {
        c[p[i]] = i;
        bit.update(n + 1, 1);
    }
    for _ in 0..n / 2 {
        let x = seg.query(0, n);
        print!("{} ", x.1 + 1);
        let k = bit.query(c[x.1] + 1);
        let r = bit.lower_bound(k + 1).0;
        let y = seg.query(c[x.1] + 1, r);
        print!("{} ", y.1 + 1);
        seg.update(c[x.1], id);
        seg.update(c[y.1], id);
        bit.update(c[x.1] + 1, 1);
        bit.update(c[y.1] + 1, 1);
    }
    println!("");
}