不难看出问题就是求极长下降子序列的长度。有经典的 O ( n log 2 n ) O(n\log^2 n) O(nlog2n)的线段树做法,但是无法通过。
这么优秀的算法你还想着优化它?
考虑扫描位置,然后用线段树维护每个询问。发现问题转化为每次对一段区间取 min \min min,然后每个位置被改变的次数就是答案。
这个可以用 Segment Tree Beats \text{Segment\ Tree\ Beats} Segment Tree Beats维护。复杂度 O ( n log n ) O(n\log n) O(nlogn)。
什么是 Segment Tree Beats \text{Segment\ Tree\ Beats} Segment Tree Beats?具体来说,对于线段树上每个节点,考虑维护 m x [ i ] mx[i] mx[i]表示节点 i i i对应区间的最大值, c x [ i ] cx[i] cx[i]表示节点 i i i对应区间的次大值,定义一个节点的势能函数为区间内不同的权值的数目。显然初始总势能为 n log n n\log n nlogn,又因为整个操作过程中没有让势能增大的操作,所以我们只需要在 O ( 1 ) O(1) O(1)的时间内解决 O ( 1 ) O(1) O(1)的势能即可。可以这样维护:
1.1
1.1
1.1 如果
c
≥
m
x
[
i
]
c\ge mx[i]
c≥mx[i],那么返回;
1.2
1.2
1.2 如果c
>
c
x
[
i
]
>cx[i]
>cx[i],那么只有区间最大值会被修改,给这个点打上标记,然后返回;
1.3
1.3
1.3 否则
c
x
[
i
]
cx[i]
cx[i]和
m
x
[
i
]
mx[i]
mx[i]都会变成
c
c
c,这样势能至少减少
1
1
1,所以复杂度是对的。
这样就做完了。
#include<bits/stdc++.h>
#define ll long long
#define fi first
#define se second
#define pb push_back
#define inf 0x3f3f3f3f
using namespace std;
const int N=1e6+5;
int n,Q,a[N],ans[N];
vector<pair<int,int>>ops[N];
vector<int>querys[N];
struct node{
//fixed
//s:区间最大值的修改次数
int mx,cx,s;
}t[N<<2];
inline int Max(int x,int y){return x>y?x:y;}
void pushup(int p){
t[p].mx=Max(t[p<<1].mx,t[p<<1|1].mx);
t[p].cx=Max(t[p<<1].cx,t[p<<1|1].cx);
if(t[p<<1].mx!=t[p].mx)t[p].cx=Max(t[p].cx,t[p<<1].mx);
if(t[p<<1|1].mx!=t[p].mx)t[p].cx=Max(t[p].cx,t[p<<1|1].mx);
}
void pushdown(int p){
if(t[p<<1].mx>t[p].mx){
t[p<<1].s+=t[p].s;
t[p<<1].mx=t[p].mx;
}
if(t[p<<1|1].mx>t[p].mx){
t[p<<1|1].s+=t[p].s;
t[p<<1|1].mx=t[p].mx;
}
t[p].s=0;
}
void modify(int p,int l,int r,int ql,int qr,int val){
if(ql<=l&&r<=qr&&val>=t[p].mx)return;
if(ql<=l&&r<=qr&&val>t[p].cx){
t[p].mx=val,t[p].s++;
return;
}
int mid=l+r>>1;pushdown(p);
if(ql<=mid)modify(p<<1,l,mid,ql,qr,val);
if(mid<qr)modify(p<<1|1,mid+1,r,ql,qr,val);
pushup(p);
}
inline int query(int p,int l,int r,int x){
if(l==r)return t[p].s;
int mid=l+r>>1;pushdown(p);
return x<=mid?query(p<<1,l,mid,x):query(p<<1|1,mid+1,r,x);
}
inline int read(){
int x=0;char c=getchar();
while(c<'0'||c>'9')c=getchar();
while(c>='0'&&c<='9')x=x*10+c-'0',c=getchar();
return x;
}
signed main(){
n=read(),Q=read();
for(int i=1;i<=n;i++)a[i]=read();
for(int i=1;i<=Q;i++){
int type,x,v;
type=read();
if(type==1){
x=read(),v=read();
ops[x].pb({i,v});
}
else{
x=read();
querys[x].pb(i);
}
}
for(int i=1;i<=4*Q;i++)t[i].mx=inf,t[i].cx=-inf;
for(int i=n;i>=1;i--){
int lst=0,val=a[i];
for(auto x:ops[i]){
modify(1,1,Q,lst+1,x.fi,val);
lst=x.fi,val=x.se;
}if(lst+1<=Q)modify(1,1,Q,lst+1,Q,val);
for(auto x:querys[i]){
ans[x]=query(1,1,Q,x);
}
}
for(int i=1;i<=Q;i++){
if(ans[i])printf("%d\n",ans[i]);
}
}