1259:【例9.3】求最长不下降序列
设有由n(1≤n≤200)个不相同的整数组成的数列,记为:b(1)、b(2)、……、b(n)若存在i1<i2<i3<…<ie 且有b(i1)<=b(i2)<=…<=b(ie)则称为长度为e的不下降序列。程序要求,当原数列出之后,求出最长的不下降序列。
例如13,7,9,16,38,24,37,18,44,19,21,22,63,15。例中13,16,18,19,21,22,63就是一个长度为7的不下降序列,同时也有7 ,9,16,18,19,21,22,63组成的长度为8的不下降序列。
输入
第一行为n,第二行为用空格隔开的n个整数。
输出
第一行为输出最大个数max(形式见样例);
第二行为max个整数形成的不下降序列,答案可能不唯一,输出一种就可以了,本题进行特殊评测。
输入
14
13 7 9 16 38 24 37 18 44 19 21 22 63 15
输出
max=8
7 9 16 18 19 21 22 63
#include <bits/stdc++.h>
using namespace std;
const int N=100000+10;
const int INF=0x3f3f3f3f;
int n,f[N],a[N],st[N],res,tot,last[N],ans[N];
int main(){
memset(st,-INF,sizeof(st));
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
for(int i=1;i<=n;i++){
f[i]=1;
if(st[tot]<=a[i]){
st[++tot]=a[i];
last[i]=tot;//输出标记
}
else {
int k=upper_bound(st+1,st+1+tot,a[i])-st;//可相等
//lower_bound(st+1,st+1+tot,a[i])-st; //严格上升序列
st[k]=a[i];
last[i]=k;//输出标记
}
}
cout<<"max="<<tot<<endl;
//输出标记
int len=tot;
for(int i=n;i;i--){
if(last[i]==len)ans[len--]=a[i];
if(len==0)break;
}
for(int i=1;i<=tot;i++)
cout<<ans[i]<<" ";
cout<<endl;
return 0;
}
具体参考https://www.cnblogs.com/DeepJay/p/12025187.html