动态规划--LIS

  LIS指一个序列中最长的单调递增(严格)的子序列。有一种较为朴素的O(n^2)的做法,我们不多做赘述,我们讲一种用单带栈和二分来实现的O(logn)的算法

  我们从1-n枚举,若该数比栈顶元素大,那么我们就将该数压入栈中。否则我们就在整个栈中二分到一个第一个大于等于它的数,将其用a[i]替换。

  考虑为什么这样可行,显然若我们二分到的数不是栈顶元素,就不会对答案产生影响。只有我们改变了栈顶元素,那么相当于此时栈中的元素才构成一个单增的子序列。二分改变非栈顶值,只是为了防止我们将未来可能产生的最优解漏掉

n=read();
for(int i=1;i<=n;i++) a[i]=read();
for(int i=1;i<=n;i++)
{
    if(top==0||stk[top]<a[i])
        stk[++top]=a[i];
    else
        *lower_bound(stk+1,stk+1+top,a[i])=a[i];
}
printf("%d\n",top);

总体代码如下:

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
inline int read()
{
    register int p(1),a(0);register char ch=getchar();
    while((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
    ch=='-'?p=-1,ch=getchar():p;
    while(ch>='0'&&ch<='9') a=a*10+ch-48,ch=getchar();
    return a*p;
}
const int N=100100;
int n,a[N],stk[N],top;
int main()
{
    n=read();
    for(int i=1;i<=n;i++) a[i]=read();
    for(int i=1;i<=n;i++)
    {
        if(top==0||stk[top]<a[i])
            stk[++top]=a[i];
        else
            *lower_bound(stk+1,stk+1+top,a[i])=a[i];
    }
    printf("%d\n",top);
    return 0;
}

 

posted @ 2018-11-20 20:41  cold_cold  阅读(223)  评论(0编辑  收藏  举报