标签:iostream cstring iter can vector input cond ring algo
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:
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.
Example
5
1 3 2 5 4
1 3 5
2 4
4
4 3 2 1
4
3
2
1
4
10 30 50 101
10 30 50 101
题解:看了网上的题解,这道题有个性质,“这些”不一定连续的上升子序列的最后一个数是有序的,如{1,3,“5”},{2,“4”},看得出来是降序。(再多几个
序列更明显),所以用一个数组存每个序列的最后一个值,然后二分查找第一个小于它的值的位置,然后更新这个位置的值。
1 #include<vector> 2 #include<cstdio> 3 #include<cstring> 4 #include<iostream> 5 #include<algorithm> 6 using namespace std; 7 8 const int maxn=2e5+10; 9 10 struct node{ 11 int x,num; 12 bool operator<(const node& i)const{ 13 if(num==i.num) return x<i.x; //!!!!! 14 return num<i.num; 15 } 16 }a[maxn]; 17 18 int n,temp[maxn]; 19 20 int main() 21 { while(cin>>n){ 22 for(int i=1;i<=n;i++) scanf("%d",&a[i].x); 23 int cnt=1; 24 for(int i=1;i<=n;i++){ 25 if(a[i].x<temp[cnt]){ //先判断,可以看作是一个优化 26 a[i].num=++cnt; 27 temp[cnt]=a[i].x; 28 continue; 29 } 30 for(int j=1;j<=cnt;j++){ 31 if(a[i].x>temp[j]){ 32 a[i].num=j; 33 temp[j]=a[i].x; 34 break; 35 } 36 } 37 } 38 39 sort(a+1,a+n+1); 40 for(int i=1;i<n;i++) printf("%d%c",a[i].x,a[i].num==a[i+1].num?‘ ‘:‘\n‘); 41 printf("%d\n",a[n].x); 42 } 43 return 0; 44 }
1 #include<vector> 2 #include<cstdio> 3 #include<cstring> 4 #include<iostream> 5 #include<algorithm> 6 using namespace std; 7 8 const int maxn=2e5+10; 9 10 int n; 11 int a[maxn]; 12 13 vector<int> G[maxn]; 14 15 int main() 16 { cin>>n; 17 18 for(int i=1;i<=n;i++){ 19 int temp; 20 scanf("%d",&temp); 21 int pos=lower_bound(a+1,a+n+1,temp)-(a+1); 22 a[pos]=temp; 23 G[pos].push_back(temp); 24 } 25 26 for(int i=n;i>0;i--) 27 for(int j=0;j<G[i].size();j++) printf("%d%c",G[i][j],j==G[i].size()-1?‘\n‘:‘ ‘); 28 }
Preparing for Merge Sort CodeForces - 847B
标签:iostream cstring iter can vector input cond ring algo
原文地址:http://www.cnblogs.com/zgglj-com/p/7667804.html