首页 > 其他 > 详细

最长子序列学习总结

时间:2014-02-19 16:15:15      阅读:313      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
//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 = upper_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;
}
bubuko.com,布布扣

最长子序列学习总结

原文:http://www.cnblogs.com/xiaoshanshan/p/3554845.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!