最长增长子序列 DP
#include<iostream> using namespace std; #define INF 0x7fffffff #define N 10000 // O(n^2) int len[N]; int dp(int *a, int n){ int mx = 0, mxlen = 1; for (int i = 0; i < n; ++i) len[i] = 1; for (int i = 1; i < n; ++i){ mx = 0; for (int j = 0; j < i; ++j) // 寻找len[0...i-1]最大值 if (a[j]<a[i] && len[j]>mx) mx = len[j]; len[i] = mx + 1; if (mxlen < len[i]) mxlen = len[i]; // 更新最大长度 } return mxlen; } // O(nlogn) int mv[N]; //mv[i]存放序列长度为 i+1 的最小元素 int binarySearch(int r, int val) { int left = 0, right = r, mid; while (left < right){ mid = (left + right) / 2; if (mv[mid] < val) left = mid + 1; else right = mid; } return left; } int binaryLIS(int *a, int n) { int len = 0; mv[0] = a[0]; for (int i = 1; i < n; ++i){ if (a[i]>mv[len]) mv[++len] = a[i]; else mv[binarySearch(len, a[i])] = a[i]; for (int i = 0; i < len; ++i) cout << mv[i] << ' '; cout << mv[len] << endl; } return len + 1; } int main() { int a[] = { 1, 7, 3, 5, 9, 4, 8 }; cout << dp(a, 7) << endl; cout << binaryLIS(a, 7) << endl; }