<题目链接>
题目大意:
裸的DP最长上升子序列,给你一段序列,求其最长上升子序列的长度,n^2的dp朴素算法过不了,这里用的是nlogn的算法,用了二分查找。
O(nlogn)算法
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int N= 1e5+5; int a[N],rise[N]; int main(){ int n;while(~scanf("%d",&n)){ memset(rise,0,sizeof(rise)); for(int i=0;i<n;i++)scanf("%d",&a[i]); int len=0; rise[0]=-1e9; for(int i=0;i<n;i++){ if(a[i]>rise[len])rise[++len]=a[i]; else{ int j=lower_bound(rise+1,rise+1+len,a[i])-rise; rise[j]=a[i]; } } printf("%d ",len); } }
虽然(n^2)算法过不了此题,但是还是先记录下
#include<cstdio> int main() { int i, j, n; int dp[1005], a[1005]; while (scanf("%d", &n) != EOF) { int max = 1; for (i = 0; i<n; i++) scanf("%d", &a[i]); dp[0] = 1; for (i = 1; i<n; i++) { dp[i] = 1; for (j = 0; j<i; j++) if (a[j]<a[i] && dp[j] + 1>dp[i]) dp[i] = dp[j] + 1; } for (i = 0; i<n; i++) if (max<dp[i]) max = dp[i]; printf("%d ", max); } }