题解:P2075 区间 LIS
yangzichen1203 · · 题解
设答案为
只要预处理出
把
对值域分治,求出值域两侧点集,然后在值域两侧补上对侧的位置。对于任意一个序列区间
分界位置
现在只需要求两个平面取
归并套归并的时间复杂度显然为
空间复杂度
提交记录:https://www.luogu.com.cn/record/308003391,轻松通过,甚至比大部分
:::success[Code]
#include<bits/stdc++.h>
#define For(i,j,k) for(int i=(j);i<=(k);i++)
#define dFor(i,j,k) for(int i=(j);i>=(k);i--)
using namespace std;
#define MAXN 100005
#define INF (1<<30)
int n,q,a[MAXN],pos[MAXN];
struct Node{
int u,v;
};
int lv[MAXN],rv[MAXN],lu[MAXN],ru[MAXN];
vector<Node> merge(int L,int R,const vector<Node> &vl,const vector<Node> &vr,const vector<int> &now){
if(vl.empty()||vr.empty()){
return {};
}
if(L==R){
return {{vl[0].u,vr[0].v}};
}
int mid=(L+R)>>1;
int pos=now[mid];
vector<Node> al,ar,bl,br;
for(auto [u,v]:vl){
(v<=pos?al:ar).push_back({u,v});
}
for(auto [u,v]:vr){
(u<=pos?bl:br).push_back({u,v});
}
vector<Node> tl=merge(L,mid,al,bl,now);
vector<Node> tr=merge(mid+1,R,ar,br,now);
for(auto [u,v]:vl){
lv[u]=INF;
rv[u]=(v<=pos?0:INF);
}
for(auto [u,v]:vr){
lu[v]=(u>pos?INF:0);
ru[v]=0;
}
for(auto [u,v]:tl){
lv[u]=v;
lu[v]=u;
}
for(auto [u,v]:tr){
rv[u]=v;
ru[v]=u;
}
int i=0,j=vr.size();
int cl=tl.size()+br.size();
int cr=tr.size()+al.size();
vector<Node> ans;
for(Node p:vl){
while(j>0){
int v=vr[j-1].v;
int ncl=cl-(lu[v]>i);
int ncr=cr-(ru[v]>i);
if(ncl<ncr) break ;
cl=ncl;
cr=ncr;
j--;
}
int col=(j==0?0:vr[j-1].v);
int fst=(cr<=cl?col:INF);
int v=(p.v<=pos?min(lv[p.u],fst):max(rv[p.u],fst));
if(v!=INF){
ans.push_back({p.u,v});
}
cl-=(lv[p.u]<=col);
cr-=(rv[p.u]<=col);
i=p.u;
}
return ans;
}
vector<Node> solve(int L,int R){
if(L==R){
return {};
}
int mid=(L+R)>>1;
vector<Node> vl=solve(L,mid);
vector<Node> vr=solve(mid+1,R);
For(i,mid+1,R){
vl.push_back({pos[i],pos[i]});
}
For(i,L,mid){
vr.push_back({pos[i],pos[i]});
}
sort(vl.begin(),vl.end(),[&](Node a,Node b){
return a.u<b.u;
});
sort(vr.begin(),vr.end(),[&](Node a,Node b){
return a.v<b.v;
});
vector<int> now;
For(i,L,R){
now.push_back(pos[i]);
}
sort(now.begin(),now.end());
return merge(0,R-L,vl,vr,now);
}
vector<pair<int,int>> e[MAXN];
int ans[MAXN];
namespace BIT{
int tr[MAXN];
void add(int x,int k){
while(x){
tr[x]+=k;
x-=x&-x;
}
}
int query(int x){
int ans=0;
while(x<=n){
ans+=tr[x];
x+=x&-x;
}
return ans;
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cin>>n>>q;
For(i,1,n){
cin>>a[i];
pos[a[i]]=i;
}
vector<Node> p=solve(1,n);
for(auto [u,v]:p){
e[v].push_back({u,0});
}
For(i,1,q){
int l,r;
cin>>l>>r;
e[r].push_back({l,i});
ans[i]=r-l+1;
}
For(i,1,n){
for(auto [l,id]:e[i]){
if(id==0){
BIT::add(l,1);
}else{
ans[id]-=BIT::query(l);
}
}
}
For(i,1,q){
cout<<ans[i]<<'\n';
}
return 0;
}
:::