1. 程式人生 > >Preparing for Merge Sort 【CodeForces

Preparing for Merge Sort 【CodeForces

 這真的是一道很不錯的題,告誡了我很多時候遇到上升序的題,要去擅於使用二分來解決問題,尤其是這次的lower_bound(),說實話,我還真的不是擅長寫lower_bound(),這次的題算是給我漲了個教訓吧。

Ivan has an array consisting of n different integers. He decided to reorder all elements in increasing order. Ivan loves merge sort so he decided to represent his array with one or several increasing sequences which he then plans to merge into one sorted array.

Ivan represent his array with increasing sequences with help of the following algorithm.

While there is at least one unused number in array Ivan repeats the following procedure:

  • iterate through array from the left to the right;
  • Ivan only looks at unused numbers on current iteration;
  • if current number is the first unused number on this iteration or this number is greater than previous unused number on current iteration, then Ivan marks the number as used and writes it down.

For example, if Ivan's array looks like [1, 3, 2, 5, 4] then he will perform two iterations. On first iteration Ivan will use and write numbers [1, 3, 5], and on second one — [2, 4].

Write a program which helps Ivan and finds representation of the given array with one or several increasing sequences in accordance with algorithm described above.

Input

The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of elements in Ivan's array.

The second line contains a sequence consisting of distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — Ivan's array.

Output

Print representation of the given array in the form of one or more increasing sequences in accordance with the algorithm described above. Each sequence must be printed on a new line.

Examples

Input

5
1 3 2 5 4

Output

1 3 5 
2 4 

Input

4
4 3 2 1

Output

4 
3 
2 
1 

Input

4
10 30 50 101

Output

10 30 50 101 
//Preparing for Merge Sort CodeForces - 847B
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
using namespace std;
typedef long long ll;
const int maxN=200005;
queue<int> Q[maxN];
int N;
int now_max[maxN];
int cnt;
int main()
{
    while(scanf("%d",&N)!=EOF)
    {
        memset(now_max, 0, sizeof(now_max));
        cnt=200000;
        for(int i=1; i<=N; i++)
        {
            int e1;
            scanf("%d",&e1);
            int place=(int)(lower_bound(now_max+1, now_max+200001, e1)-now_max);
            place--;
            now_max[place]=e1;
            Q[place].push(e1);
            if(place<cnt) cnt=place;
        }
        for(int i=200000; i>=cnt; i--)
        {
            while(Q[i].size())
            {
                printf("%d",Q[i].front());
                if(Q[i].size()>1) printf(" ");
                Q[i].pop();
            }
            printf("\n");
        }
    }
    return 0;
}