最长递增子序列
一个是O(n^2)一个是O(logn*n)
两者都需要临时空间
#include <iostream> using namespace std; //time complex:n^n int longest_increase_sequence(int a[], int n) { if(n==1) return n; int b[n]; int i,j; int tmp, result=1; b[0] = 1; for(i=1;i<n;i++) { tmp= 1; for(j=0;j<i;j++) { if(b[j]>=tmp&&a[j]<=a[i]) tmp = b[j] +1; } b[i] = tmp; if(b[i]>result) result = b[i]; } return result; } //length increased return true bool binary_replace(int a[], int n, int val) { if(n==0) { a[0] = val; return true; } int i; for(i=0;i<n;i++) { if(a[i]>val) { a[i] = val; return false; } } if(i==n) { a[n] = val; return true; } } int longest_increase_sequence2(int a[], int n) { if(n<=1) return n; int b[n]; int result = 1; int len = 1; b[0] = a[0]; for(int i=1;i<n;i++) { if(binary_replace(b,len,a[i])) len++; } return len; } int main() { int n; int a[100]; while(cin>>n) { for(int i=0;i<n;i++)cin>>a[i]; cout<<longest_increase_sequence(a,n)<<endl; cout<<longest_increase_sequence2(a,n)<<endl; } return 0; }
每天早上叫醒你的不是闹钟,而是心中的梦~