NYOJ_201_作业题
最长递增递减子序列
我的代码:
#include<iostream> #include<cstdio> #include<algorithm> #include<cmath> #include<cstring> #include<string> using namespace std; struct point { int x,y; }p[1005]; int dp[1004]; bool cmp(point a,point b) { return a.x>b.x; } int main() { int t,n,i,j,re[1005]; scanf("%d",&t); while(t--) { scanf("%d",&n); for(i=0;i<n;++i) scanf("%d%d",&p[i].x,&p[i].y); sort(p,p+n,cmp);//必不可少 int num=0; re[0]=-1; for(i=0;i<n;++i) //最长递增子序列 { for(j=num;j>=0;--j) if(p[i].y>re[j]) { re[j+1]=p[i].y; if(j+1==num+1) num++; break; } } int sec=0; re[0]=10005; for(i=0;i<n;++i) //最长递减子序列 for(j=sec;j>=0;--j) if(p[i].y<re[j]) { re[j+1]=p[i].y; if(j+1==sec+1) sec++; break; } printf("%d\n",num>sec?num:sec);//递增长还是递减长? } return 0; }
高手的代码:
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<functional> using namespace std; #define CLR(arr,val) memset(arr,val,sizeof(arr)) const int MAX=10010; int y[MAX],tmp[MAX],tmp2[MAX]; int main() { int t,n,x,top1,top2; scanf("%d",&t); while(t--) { CLR(y,0); scanf("%d",&n); for(int i=0;i!=n;i++) { scanf("%d",&x); scanf("%d",&y[x-1]); } top1=top2=0; int num=remove(y,y+MAX,0)-y; for(int i=0;i!=num;i++) { int *p=lower_bound(tmp,tmp+top1,y[i]); int *q=lower_bound(tmp2,tmp2+top2,y[i],greater<int>()); if(p-tmp==top1) ++top1; if(q-tmp2==top2) ++top2; *p=y[i]; *q=y[i]; } printf("%d\n",max(top1,top2)); } }