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)

#![allow(unused_imports)]
#![allow(non_snake_case)]
use std::cmp::*;
use std::collections::*;
use std::io::Write;

#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), std::io::stderr());
            writeln!(err, "{} = {:?}", e, $e).unwrap()
        })*
    };
}

fn get_next<F>(
    begin: usize,
    end: usize,
    e_tree: &SegTree<usize, F>,
    o_tree: &SegTree<usize, F>,
    pos: &Vec<usize>,
) -> (usize, usize)
where
    F: Fn(usize, usize) -> usize,
{
    if begin % 2 == 0 {
        let next_first = e_tree.query(begin, end - 1);
        let next_end = o_tree.query(pos[next_first], end);
        (next_first, next_end)
    } else {
        let next_first = o_tree.query(begin, end - 1);
        let next_end = e_tree.query(pos[next_first], end);
        (next_first, next_end)
    }
}

fn main() {
    let n = read::<usize>();
    let p = read_vec::<usize>();

    let mut pos = vec![0; n + 1];
    for i in 0..n {
        pos[p[i]] = i;
    }

    let mut e_tree = SegTree::new(n, std::usize::MAX, std::cmp::min);
    let mut o_tree = SegTree::new(n, std::usize::MAX, std::cmp::min);

    for i in 0..n {
        if i % 2 == 0 {
            e_tree.update(i, p[i]);
        } else {
            o_tree.update(i, p[i]);
        }
    }
    let mut heap = BinaryHeap::new();
    let first = e_tree.query(0, n);
    let second = o_tree.query(pos[first], n);
    heap.push((-(first as i64), -(second as i64), 0, n));
    let mut answers = vec![];

    while let Some((first, second, begin, end)) = heap.pop() {
        let first = -first as usize;
        let second = -second as usize;
        answers.push(first);
        answers.push(second);
        let first = pos[first];
        let second = pos[second];
        debug!(first, second);
        if first - begin > 1 {
            let (next_first, next_end) = get_next(begin, first, &e_tree, &o_tree, &pos);
            heap.push((-(next_first as i64), -(next_end as i64), begin, first));
        }
        if second - first > 2 {
            let (next_first, next_end) = get_next(first + 1, second, &e_tree, &o_tree, &pos);
            heap.push((-(next_first as i64), -(next_end as i64), first + 1, second));
        }
        if end - second > 2 {
            let (next_first, next_end) = get_next(second + 1, end, &e_tree, &o_tree, &pos);
            heap.push((-(next_first as i64), -(next_end as i64), second + 1, end));
        }
        debug!(heap);
    }

    for ans in answers {
        print!("{} ", ans);
    }
    println!("");
}

fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}

struct SegTree<T, F>
where
    F: Fn(T, T) -> T,
    T: std::clone::Clone + std::marker::Copy,
{
    n: usize,
    dat: Vec<T>,
    init: T,
    functor: F,
}

impl<T, F> SegTree<T, F>
where
    F: Fn(T, T) -> T,
    T: std::clone::Clone + std::marker::Copy,
{
    fn new(n: usize, init: T, f: F) -> SegTree<T, F> {
        let mut m = 1;
        // For simplicity, we use 2 ** n sized SegTree.
        while m < n {
            m *= 2;
        }
        SegTree {
            n: m,
            dat: vec![init; 2 * m - 1],
            init: init,
            functor: f,
        }
    }

    // dat[k] = a;
    fn update(&mut self, k: usize, a: T) {
        let mut k = k;
        k += self.n - 1;
        self.dat[k] = a;
        while k > 0 {
            k = (k - 1) / 2;
            self.dat[k] = (self.functor)(self.dat[k * 2 + 1], self.dat[k * 2 + 2]);
        }
    }

    // [a, b)
    fn query(&self, a: usize, b: usize) -> T {
        self.query_inner(a, b, 0, 0, self.n)
    }

    fn query_inner(&self, a: usize, b: usize, k: usize, l: usize, r: usize) -> T {
        if r <= a || b <= l {
            return self.init;
        }
        if a <= l && r <= b {
            return self.dat[k];
        }

        let vl = self.query_inner(a, b, k * 2 + 1, l, (l + r) / 2);
        let vr = self.query_inner(a, b, k * 2 + 2, (l + r) / 2, r);
        (self.functor)(vl, vr)
    }
}