题意分析
本题所求经过转化,即为最长不上升子序列和最长上升子序列。
解法介绍
这里使用数据结构优化 DP 的方法。
下文使用 表示导弹高度。
在此之前,让我们先看看两问的暴力 DP 转移式:
此时若暴力找最大值,时间复杂度为 ,不能通过本题。
我们可以使用权值树状数组维护最大值。每次查询 下标前将前 个元素的 插入树状数组,并维护 的最大值。此时,单次查询的时间复杂度为 ,总时间复杂度为 ,可以通过本题。
代码分析
#include<bits/stdc++.h>
using namespace std;
namespace IO{
const int W=1<<20;
char ibuf[W+10];
char obuf[W+10];
int itop=-1;
int isz=0;
int otop=-1;
inline char getc(){
if(itop+1==isz){
itop=-1;
isz=fread_unlocked(ibuf,1,W,stdin);
}
if(isz==0) return -1;
return ibuf[++itop];
}
inline void flush(){
fwrite_unlocked(obuf,1,otop+1,stdout);
otop=-1;
}
inline void putc(char f){
if(otop+1==W){
flush();
}
obuf[++otop]=f;
}
inline bool read(int &p){
p=0;
char f='\0';
while((f<'0' || f>'9') && f!=-1){
f=getc();
}
if(f==-1) return 0;
while('0'<=f && f<='9'){
p=p*10+(f^'0');
f=getc();
}
return 1;
}
inline void write(int p){
static char st[32];
int tp=0;
while(p){
st[++tp]=p%10;
p/=10;
}
while(tp){
putc(st[tp--]^'0');
}
return;
}
}
namespace FWK{
const int W=5e4+10;
int tree[W+10];
inline int lowbit(int x){
return x&(-x);
}
inline void insert(int x,int a){
while(x<=W){
tree[x]=max(tree[x],a);
x+=lowbit(x);
}
return;
}
inline int query(int x){
int ans=0;
while(x){
ans=max(ans,tree[x]);
x-=lowbit(x);
}
return ans;
}
inline void clear(){
memset(tree,0,sizeof(tree));
}
}
const int N=1e5;
int a[N+10];
int main(){
int n=0;
while(IO::read(a[n+1])) n++;//读入 1~n
for(int i=1;i<=n;i++){
FWK::insert(FWK::W-a[i],FWK::query(FWK::W-a[i])+1);//query 得到的是>=a[i]元素的dp最大值,此处之所以使用W-a[i]是为了将大于关系转为小于关系,方便树状数组的实现。之后随即将自身插入树状数组供后面元素查询。
}
IO::write(FWK::query(FWK::W));//此处查询所有dp值中的最大值。
IO::putc('\n');
FWK::clear();
for(int i=1;i<=n;i++){
FWK::insert(a[i],FWK::query(a[i]-1)+1);//和上面同理,但是由于序列严格单调所以 a[i]-1。
}
IO::write(FWK::query(FWK::W));
IO::flush();//撒花.
return 0;
}