最长子序列学习总结
//upper_bound 在数列1 2 3 4 5 6中 upper_bound(3) 返回的位置为4 //lower_bound 返回的值为3 //此算法 是 贪心和二分查找的升级版 #include <cstdio> #include <algorithm> #include <iostream> using namespace std; const int maxn = 100000; int dp[maxn],s[maxn],a[maxn]; void DP(int *s,int *dp,int n) { // s 中存的是最长的上升子序列;dp[i]存的是第i个数为结尾的最长上升子序列; int top=0,temp; s[top++] = a[0]; dp[0] = 1; for (int i=1;i<n;i++) { if (s[top-1] <= a[i]) { s[top++] = a[i]; temp = top; } else { int x = lower_bound(s,s+top,a[i])-s;//返回第一个比a[i]大的数的位置; s[x] = a[i]; temp = x+1; } dp[i] = temp; } } int main () { int n; cin >> n; for (int i=0;i<n;i++) { cin >> a[i]; } DP(s,dp,n); int max_length=1; for (int i = 0;i < n; i++) { max_length = max (max_length,dp[i]); } cout << max_length << endl; }