poj2533 - Longest Ordered Subsequence(简单动规)
状态:d[i]表示a[1.....i]的最长上升子序列
状态转移:d[i] = max{d[j]+1|a[i]>a[j]}
代码如下:
#include <cstdio> #include <cstring> #define N 1005 int n, a[N], d[N]; int main () { int max; while(~scanf("%d",&n)) { for(int i = 1; i <= n; i++) scanf("%d",&a[i]); memset(d,0,sizeof(d)); d[1] = 1; max = 1; for(int i = 2; i <= n; i++) { int &ans = d[i]; ans = 1; for(int j = 1; j < i; j++) { if(a[i]>a[j]&&ans<d[j]+1) ans = d[j]+1; } if(max<d[i]) max = d[i]; } printf("%d\n",max); } return 0; }
o(nlogn)算法
代码如下:
#include <cstdio> #include <cstring> #define N 1005 int n, a[N], c[N], dp[N]; int search(int l, int r, int x) { int mid; while(l<=r) { mid = (r+l)/2; if(c[mid]==x) return mid; else if(x>c[mid]) l = mid+1; else r = mid-1; } return l; } int main() { while(~scanf("%d",&n)) { for(int i = 1; i <= n; i++) scanf("%d",&a[i]); c[1] = a[1]; dp[1] = 1; int size = 1; for(int i = 2, j; i <= n; i++) { if(a[i]<c[1]) j = 1; else if(a[i]>c[size]) j = ++size; else j = search(1,size, a[i]); c[j] = a[i]; } printf("%d\n",size); } return 0; }