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)

// https://atcoder.jp/contests/arc080/tasks/arc080_c
//
#![allow(unused_imports)]
use std::io::*;
use std::io::Write;
use std::fmt::*;
use std::str::*;
use std::cmp::*;
use std::collections::*;

// Input macros.
// Original by tanakh: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        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)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };

    ($iter:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

#[allow(unused_macros)]
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, [ next / $t:tt ]) => {
        {
            let len = read_value!($iter, usize);
            (0..len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
        }
    };

    ($iter:expr, switch) => {
        {
            let ty = read_value!($iter, i32);
            if ty == 1 {
                vec![ty, read_value!($iter, i32), read_value!($iter, i32)]
            } else if ty == 2 {
                vec![ty, read_value!($iter, i32)]
            } else {
                vec![ty, read_value!($iter, i32)]
            }
        }
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_macros)]
macro_rules! read_line {
    ($t:tt) => {
        {
            let mut s = String::new();
            std::io::stdin().read_line(&mut s).unwrap();
            s.trim_right().parse::<$t>().unwrap()
        }
    }
}

#[allow(unused_macros)]
macro_rules! dvec {
    ($t:expr ; $len:expr) => {
        vec![$t; $len]
    };

    ($t:expr ; $len:expr, $($rest:expr),*) => {
        vec![dvec!($t; $($rest),*); $len]
    };
}

#[allow(unused_macros)]
macro_rules! ifv {
    ($t:expr, $a:expr, $b: expr) => {
        if $t { $a } else { $b }
    }
}

#[allow(unused_macros)]
macro_rules! fill {
    ($t:expr, $v:expr) => {
        for i in 0..$t.len() {
            $t[i] = $v;
        }
    };
}

#[allow(unused_macros)]
macro_rules! join {
    ($t:expr, $glue:expr) => {
        $t.into_iter().map(|w| w.to_string()).collect::<Vec<_>>().join($glue)
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

// ===

// ====

use std::rc::Rc;
type Merger<T> = Rc<Fn(T, T) -> T>;

struct SegmentTree<T> {
    n: usize,
    default: T,
    bottom_offset: usize,
    data: Vec<T>,
    merger: Merger<T>,
}

impl<T: Debug + Copy + Eq> SegmentTree<T> {
    fn new(n: usize, initial: T, merger: Merger<T>) -> Self {
        let z = (8u32 * std::mem::size_of::<usize>() as u32) - n.leading_zeros();
        let size = (1<<z) as usize;
        SegmentTree {
            n: size*2,
            default: initial,
            bottom_offset: size,
            data: vec![initial; size*2],
            merger: merger,
        }
    }

    /// Change single position [i, i+1) to value v.
    fn set(&mut self, i: usize, v: T) {
        let mut idx = self.bottom_offset + i;
        self.data[idx] = v;
        while idx >= 1 {
            idx /= 2;
            self.data[idx] = (self.merger)(self.data[idx*2], self.data[idx*2+1]);
        }
    }

    /// Get single position value.
    fn get(&mut self, i: usize) -> T {
        self.data[self.bottom_offset+i]
    }

    /// Apply merge with v to single position [i, i+1).
    fn apply(&mut self, i: usize, v: T) {
        let mut idx = self.bottom_offset + i;
        while idx >= 1 {
            self.data[idx] = (self.merger)(self.data[idx], v);
            idx /= 2;
        }
    }

    /// Compute value [i, j).
    fn compute_range(&self, mut i: usize, mut j: usize) -> T {
        if i >= j {
            return self.default;
        }
        let mut result_left = self.default;
        let mut result_right = self.default;
        i += self.bottom_offset;
        j += self.bottom_offset;
        while i != j {
            if i & 1 == 1 {
                result_left = (self.merger)(result_left, self.data[i]);
                i += 1;
            }
            if j & 1 == 1 {
                j -= 1;
                result_right = (self.merger)(self.data[j], result_right);
            }
            i >>= 1;
            j >>= 1;
        }
        (self.merger)(result_left, result_right)
    }

    fn merge(&mut self, i: usize, j: usize) -> T {
        (self.merger)(self.data[i], self.data[j])
    }

    fn debug_print(&self, from: usize, to: usize) {
        for i in from..to {
            debug!(i, self.data[self.bottom_offset+i]);
        }
        debug!(from, to, self.compute_range(from, to));
    }
}

// ====

fn main() {
    input! {
        n: usize,
        q: [i32; n]
    };

    let INF = 1e9 as i32;
    let mut odd = SegmentTree::new(n, (INF,n), Rc::new(|a,b| min(a,b)));
    let mut even = SegmentTree::new(n, (INF,n), Rc::new(|a,b| min(a,b)));
    for i in 0..n {
        if i % 2 == 0 {
            odd.set(i, (INF, i));
            even.set(i, (q[i], i));
        } else {
            odd.set(i, (q[i], i));
            even.set(i, (INF, i));
        }
    }

    let extract = |l:usize, r:usize| {
        if l + 1 == r {
            return (-q[l], -q[r], vec![]);
        }
        let mut parts = vec![];
        let e = ifv!(l % 2 == 0, even.compute_range(l, r+1), odd.compute_range(l, r+1));
        let o = ifv!(l % 2 == 0, odd.compute_range(e.1, r+1), even.compute_range(e.1, r+1));
        let ll = e.1;
        let rr = o.1;
        if l < ll {
            parts.push((l, ll-1));
        }
        if ll+1 < rr {
            parts.push((ll+1, rr-1));
        }
        if rr+1 < r {
            parts.push((rr+1, r));
        }
        (-e.0, -o.0, parts)
    };

    let mut q = BinaryHeap::new();
    q.push(extract(0, n));
    let mut ans = vec![];
    while let Some((v1, v2, parts)) = q.pop() {
        ans.push(-v1);
        ans.push(-v2);
        for p in parts {
            q.push((extract(p.0, p.1)));
        }
    }
    println!("{}", join!(ans, " "));
}