G - 最长上升子序列
Time Limit: 3000/1000MS (Java/Others) Memory Limit: 65535/65535KB (Java/Others)
一个数的序列 B=(b1,b2,⋯,bS) B=(b1,b2,⋯,bS),当 b1<b2<⋯<bS b1<b2<⋯<bS 的时候,我们称这个序列是上升的。对于给定的一个序列 A=(a1,a2,⋯,aN) A=(a1,a2,⋯,aN),我们可以得到一些上升的子序列 (ai1,ai2,⋯,aiK) (ai1,ai2,⋯,aiK),这里 1≤i1<i2<⋯<iK≤N 1≤i1<i2<⋯<iK≤N。比如,对于序列 (1,7,3,5,9,4,8) (1,7,3,5,9,4,8),有它的一些上升子序列,如 (1,7) (1,7), (3,4,8) (3,4,8)等等。这些子序列中最长的长度是 4 4,比如子序列 (1,3,5,8) (1,3,5,8)。
你的任务,就是对于给定的序列,求出最长最小的上升子序列。所谓最长最小的子序列,是指若有多个最长子序列时,存在一个子序列 A=(as1,as2,⋯,ask) A=(as1,as2,⋯,ask),对其它任意最长子序列 B=(at1,at2,⋯,atk) B=(at1,at2,⋯,atk),有前 i−1 i−1个元素相等, 而 asi<ati asi<ati,则 A A是最长最小的上升子序列。
Input
有多组测试数据。输入的第一行是整数 T T( 0<T≤100 0<T≤100),表示测试数据的组数。每组测试数据占一行,第一个数是序列的长度 N N ( 1≤N≤1000 1≤N≤1000)。紧随其后是序列中的 N N 个整数,该行每个数后均有一个空格,这些整数的取值范围都在 0 0 到 10000 10000。该行没有其它多余的符号。
Output
对应每组输入,先输出最长最小的上升子序列长度,再输出最长最小的上升子序列,占一行。每个数后应有一个空格,该行不能有其它多余的符号。
Sample Input
1 7 1 7 3 5 9 4 8
Sample Output
4 1 3 4 8
#include<cstdio> #include<cstring> #define MAXN 1005 #include<string> #include<algorithm> using namespace std; int arr[MAXN],ans[MAXN],len; /* 二分查找。 注意,这个二分查找是求下界的; (什么是下界?详情见《算法入门经典》 P145) 即返回 >= 所查找对象的第一个位置(想想为什么) 也可以用STL的lowe_bound二分查找求的下界 */ int binary_search(int i) { int left,right,mid; left=0,right=len; while(left<right) { mid = left+(right-left)/2; if(ans[mid]>=arr[i]) right=mid; else left=mid+1; } return left; } int main() { int T,p,i,j,k; scanf("%d",&T); while(T--) { scanf("%d",&p); for(i=1; i<=p; ++i) scanf("%d",&arr[i]); ans[1] = arr[1]; len=1; int pos; int maxx=0; for(i=1; i<=p; ++i) { if(arr[i]>ans[len]) ans[++len]=arr[i]; else { int pos=binary_search(i); //stl的做法:pos=lower_bound(ans,ans+len,arr[i])-ans; //printf("pos=%d ",pos); ans[pos] = arr[i]; } if(maxx<len) maxx=len; } printf("%d ",maxx); for(i=1;i<=len;i++) printf("%d ",ans[i]); } return 0; }