题解:CF2165F Arctic Acquisition

· · 题解

好题要点赞。

思路

首先我们只需要对于每个左端点求出最小的合法右端点 p_i,有答案为 \sum n-p_i+1。

将 (i_1,i_2,i_3,i_4,i_5) 分成两组 (i_1,i_2) 和 (i_3,i_4,i_5),假设我们求出所有合法的有用组,合并的限制为 i_2<i_3\land a_{i_1}<a_{i_4},于是可以二位数点简单合并。

先考虑 (i_1,i_2),因为对于每个 i_1 来说 i_2 一定取后面第一个小于 a_{i_1} 的位置,所以可以单调栈求出。

再考虑 (i_3,i_4,i_5),这个东西看起来有非常多对,但实际上也只有 O(n) 对,有结论对于每个 i_4,i_5 一定取后面第一个大于 a_{i_4} 的位置,证明是简单的,假设存在一个 i_6 满足 i_4<i_6<i_5\land a_{i_4}<a_{i_6}<a_{i_3}<a_{i_5},则将 (i_3,i_4,i_5) 换成 (i_3,i_6,i_5) 一定不劣,求 i_5 可以用单调栈,求出 i_5 后,i_3 为 i_4 左边第一个值在 (a_{i_4},a_{i_5}) 中的位置,可以用线段树维护区间最大值求,然后做完了。

代码

#include<bits/stdc++.h>
#define int long long
using namespace std;
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
char buf[1<<23],*p1=buf,*p2=buf;
int read(){char c=getchar();int p=0,flg=1;while(c<'0'||c>'9'){if(c=='-') flg=-1;c=getchar();}while(c>='0'&&c<='9'){p=p*10+c-'0';c=getchar();}return p*flg;}
int T,n,a[1000010],st[1000010],top,f[1000010],g[1000010],h[1000010],res[1000010],c[1000010],t[2000010];vector<int>F[1000010];vector<array<int,2>>G[1000010];
void init(){for(int i=1;i<(n<<1);i++) t[i]=0;}
void modify(int x,int v){t[x+=n-1]=v;while(x>>=1) t[x]=max(t[x<<1],t[x<<1|1]);}
int query(int l,int r){
    int res=0;for(l+=n-1,r+=n;l<r;l>>=1,r>>=1){
        if(l&1) res=max(res,t[l++]);
        if(r&1) res=max(res,t[--r]);
    }return res;
}
void add(int x,int y){for(;x;x-=x&-x) c[x]=min(c[x],y);}
int ask(int x){int ans=n+1;for(;x<=n;x+=x&-x) ans=min(ans,c[x]);return ans;}
void solve(){
    n=read();for(int i=1;i<=n;i++) a[i]=read(),F[i].clear(),G[i].clear();
    top=0;for(int i=n;i;i--){
        while(top&&a[i]<a[st[top]]) top--;
        f[i]=top?st[top]:0;st[++top]=i;
    }top=0;for(int i=n;i;i--){
        while(top&&a[i]>a[st[top]]) top--;
        g[i]=top?st[top]:0;st[++top]=i;
    }init();for(int i=1;i<=n;i++){
        h[i]=g[i]?query(a[i],a[g[i]]):0;
        modify(a[i],i);
    }for(int i=1;i<=n;i++){
        if(f[i]) F[f[i]].push_back(i);
        if(g[i]&&h[i]) G[h[i]].push_back({i,g[i]});
        res[i]=c[i]=n+1;
    }for(int i=n;i;i--){
        for(auto j:F[i]) res[j]=min(res[j],ask(a[j]));
        for(auto j:G[i]) add(a[j[0]],j[1]);
    }int ans=0;for(int i=n,R=n+1;i;i--){R=min(R,res[i]);ans+=n-R+1;}cout<<ans<<'\n';
}
signed main(){
    T=read();while(T--) solve();
    return 0;
}