PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FT0000075. Phân phối phần tử vào hai dãy II (Distribute Elements Into Two Arrays II)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Phân phối phần tử vào hai dãy II (Distribute Elements Into Two Arrays II)

Distribute Elements Into Two Arrays II

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

Given n≥3n\ge3 integers a1,…,ana_1,\ldots,a_n, distribute them, in order, into two initially empty arrays B1B_1 and B2B_2 using exactly nn operations, each appending one item to one array.

First append a1a_1 to B1B_1, then append a2a_2 to B2B_2. For each later value x=aix=a_i (i≥3i\ge3), let g(B,x)g(B,x) be the number of elements in BB strictly greater than xx. Append xx to the array with larger g(B,x)g(B,x); if tied, to the shorter array; if still tied, to B1B_1.

After all insertions, concatenate B1B_1 followed by B2B_2, preserving the internal order of both. Output the resulting array of nn integers.

Input

The first line contains integer nn.

The second line contains nn integers a1,…,ana_1,\ldots,a_n in distribution order.

Output

Print nn integers on one line: all elements of B1B_1 followed by all elements of B2B_2, separated by spaces.

Subtasks

  • Subtask 1 (20 points): 3≤n≤83\le n\le 8; 1≤ai≤1091\le a_i\le 10^9 for every 1≤i≤n1\le i\le n.

  • Subtask 2 (30 points): 3≤n≤20003\le n\le 2000; 1≤ai≤1091\le a_i\le 10^9 for every 1≤i≤n1\le i\le n.

  • Subtask 3 (50 points): 3≤n≤1000003\le n\le 100000; 1≤ai≤1091\le a_i\le 10^9 for every 1≤i≤n1\le i\le n.

Examples

Input

5
5 14 3 1 2

Output

5 3 1 2 14

Explanation

The first two operations produce B1=[5]B_1=[5] and B2=[14]B_2=[14].

  • For x=3x=3: g(B1,3)=1g(B_1,3)=1 and g(B2,3)=1g(B_2,3)=1. Both arrays have equal length, so append to B1=[5,3]B_1=[5,3].
  • For x=1x=1: g(B1,1)=2g(B_1,1)=2 from 5,35,3, versus g(B2,1)=1g(B_2,1)=1. Append to B1=[5,3,1]B_1=[5,3,1].
  • For x=2x=2: g(B1,2)=2g(B_1,2)=2 from 5,35,3, versus g(B2,2)=1g(B_2,2)=1. Append to B1=[5,3,1,2]B_1=[5,3,1,2].

Finally B2=[14]B_2=[14]. Concatenation gives 5 3 1 2 14.