您的位置:首页 > 其它

最长上升子序列 和 最长不下降子序列

2015-06-01 14:31 281 查看
最长上升子序列:是严格上升的,a<b<c<d这样的,即为严格单调递增,用lower_bound

lower_bound:返回序列中大于等于key值的第一个数

比如说序列 1 2 3 4 5,key值为3,使用lower_bound返回第三个数

最长不下降子序列:不是严格上升,可以存在多个数相等的情况,用upper_bound

upper_bound:返回序列中严格大于key值的第一个数

比如说序列1 2 3 4 5,key值为3,使用upper_bound返回第四个数

Hdu 1950 求最长上升子序列

#include<iostream>
#include<cstdio>
#include<cstring>
#include <cmath>
#include<stack>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<algorithm>
using namespace std;

typedef long long LL;
const int INF = (1<<30)-1;
const int mod=1000000007;
const int maxn=1000005;

int a[maxn],f[maxn];

int main(){
int T;
scanf("%d",&T);
int kase=0;
while(T--){
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++) {
scanf("%d",&a[i]);
a[i]=a[i]-i;
}

int len=1;
f[1]=a[1];
for(int i=2;i<=n;i++){
if(a[i]>=f[len]) f[++len]=a[i];//这里也和求最长上升子序列不同,是大于等于
else{
int pos=upper_bound(f+1,f+len+1,a[i])-f;//upper_bound返回的是序列中严格大于key值的第一个数
f[pos]=a[i];
}
}
printf("Case #%d:\n",++kase);
printf("%d\n",n-len);
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: