Codeforces847b preparing formerge sort

阅读全文大概需要 3分钟
本文总阅读量
Posted by yjjr's blog on February 6, 2018

标签:递推,DP

Ivan hasan array consisting of n differentintegers. He decided to reorder all elements in increasing order. Ivan lovesmerge sort so he decided to represent his array with one or several increasingsequences which he then plans to merge into one sorted array.

Ivanrepresent his array with increasing sequences with help of the followingalgorithm.

Whilethere is at least one unused number in array Ivan repeats the followingprocedure:

·  iterate through array from the left to theright;

·  Ivan only looks at unused numbers on currentiteration;

·  if current number is the first unused numberon this iteration or this number is greater than previous unused number oncurrent iteration, then Ivan marks the number as used and writes it down.

Forexample, if Ivan's array looks like [1, 3,2, 5, 4] then he will perform two iterations. On first iterationIvan will use and write numbers [1, 3, 5], and onsecond one — [2, 4].

Write aprogram which helps Ivan and finds representation of the given array with oneor several increasing sequences in accordance with algorithm described above.

Input

The firstline contains a single integer n (1 ≤ n ≤ 2·105) — the number ofelements in Ivan's array.

The secondline contains a sequence consisting of distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — Ivan'sarray.

Output

Printrepresentation of the given array in the form of one or more increasingsequences in accordance with the algorithm described above. Each sequence mustbe printed on a new line.

Example

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

类似于noip1999拦截导弹那题

为了防止TLE,只好先前加入判断了,这样可以避免一部分的双重循环,时间复杂度O(n*cnt)

//cnt代表输出答案的行数

Code

#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define dep(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
 
inline int read()
{
       intf=1,x=0;char ch=getchar();
       while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
       while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
       returnx*f;
}
struct data{int num,x;}a[200005];
int n,cnt=1,Max[200005];
 
inline int cmp(data a,data b)
{
   if(a.num==b.num)return a.x<b.x;
       elsereturn a.num<b.num;
}
 
int main()
{
       n=read();
       rep(i,1,n)a[i].x=read();
       rep(i,1,n){
              if(a[i].x<Max[cnt]){Max[++cnt]=a[i].x;a[i].num=cnt;continue;}
              rep(j,1,cnt)if(a[i].x>Max[j]){Max[j]=a[i].x;a[i].num=j;break;}
       }
       sort(a+1,a+1+n,cmp);
       printf("%d",a[1].x);
       rep(i,2,n){
              if(a[i].num!=a[i-1].num)printf("\n");
              printf("%d",a[i].x);
       }
       return0;
}



本文可以转载,但必须附上原文链接,否则你会终生找不到妹子!!!欢迎关注我的CSDN: ahyjjr