P14989 传送 题解
mo_mo_yu0_0 · · 题解
前置知识:主席树和单调栈。
对于点
-
-
否则,
x 一定会先传送到权值最大的点。i 不合法。
对于
接下来怎么做?我们考虑对于每个点,维护它在哪些区间内可以作为最大值。显然可以单调栈。
那么题目变为了每次给定一个区间,求
#include<bits/stdc++.h>
#define int long long
#define unsigned long long ull
#define int128 __int128
#define faster ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
const int maxn=5e5+10;
int n,k,a[maxn];
int l[maxn],r[maxn];
struct hjt_tree{
int tot=0;
struct node{
int l,r,x;
}nd[maxn*28];
int root[maxn];
void pushup(int k){
nd[k].x=nd[nd[k].l].x+nd[nd[k].r].x;
}
void build(int &k,int l,int r){
k=++tot;
if(l==r){
return;
}
int mid=(l+r)>>1;
build(nd[k].l,l,mid);
build(nd[k].r,mid+1,r);
pushup(k);
}
int clone(int k){
++tot;
nd[tot]=nd[k];
return tot;
}
void change(int &k,int l,int r,int x,int dx){
k=clone(k);
if(l==r){
nd[k].x+=dx;
return;
}
int mid=(l+r)>>1;
if(x<=mid)change(nd[k].l,l,mid,x,dx);
else change(nd[k].r,mid+1,r,x,dx);
pushup(k);
}
int query(int k,int l,int r,int x,int y){
if(l>y||r<x)return 0;
if(l>=x&&r<=y)return nd[k].x;
int mid=(l+r)>>1;
return query(nd[k].l,l,mid,x,y)+query(nd[k].r,mid+1,r,x,y);
}
}tr;
vector<int>vec[maxn];
void solve(){
cin>>n>>k;
for(int i=1;i<=n;i++)cin>>a[i];
stack<pair<int,int> >s;
for(int i=1;i<=n;i++){
while(!s.empty()&&s.top().first<=a[i])s.pop();
if(s.empty())l[i]=1;
else l[i]=s.top().second+1;
s.push({a[i],i});
}
while(!s.empty())s.pop();
for(int i=n;i>=1;i--){
while(!s.empty()&&s.top().first<=a[i])s.pop();
if(s.empty())r[i]=n;
else r[i]=s.top().second-1;
s.push({a[i],i});
}
for(int i=1;i<=n;i++)vec[l[i]].push_back(r[i]);
tr.build(tr.root[0],1,n);
for(int i=1;i<=n;i++){
tr.root[i]=tr.root[i-1];
for(int j:vec[i])tr.change(tr.root[i],1,n,j,1);
}
while(k--){
int cnt;
cin>>cnt;
int minx=n,maxx=1;
while(cnt--){
int x;
cin>>x;
minx=min(minx,x);
maxx=max(maxx,x);
}
cout<<tr.query(tr.root[minx],1,n,maxx,n)<<'\n';
}
}
signed main(){
faster;
int T=1;
// cin>>T;
while(T--)solve();
}
感谢观看。