您的位置:首页 > 其它

动态规划-基础篇——最长上升子序列(nlogn)

2014-01-24 20:24 211 查看
我写这片博文就只是提醒自己不要理解而已,其中只是一个结论,其实的证明,思路啥的都没写,以后搞dp专题的时候会全部补上,这里只是一个开头。

对于最长上升子序列(LIS)问题中,一直对lower_bound(),和upper_bound()分不清楚。

用法是:如果是严格LIS,则用的是lower_bound(),

如果是非严格LIS,则用的是upper_bound();

例如对于序列{3,4,4,5,4,4,4,4,4,4,6};

则严格Lis为{3,4,5,6},长度为4

而非严格LIS为{3,4,4,4,4,4,4,6}长度为8

代码如下

#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <queue>
#include <stack>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn=30000+5;
int b[maxn],a[maxn];
int LISdp(int n)
{
int i,k;
b[1]=a[1];
for(i=2,k=1;i<=n;i++)
{
if(a[i]>=b[k])  b[++k]=a[i];
else
{
int pos=upper_bound(b+1,b+1+k,a[i])-b;//非严格
b[pos]=a[i];
}
}
return k;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out2.txt","w",stdout);
int n;
while(cin>>n){
for(int i=1;i<=n;i++){
cin>>a[i];
}
int ans=LISdp(n);
cout<<n-ans<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: