题解:P15412 「TBOI Round 1」Niton & Galgame

· · 题解

P15412 「TBOI Round 1」Niton & Galgame - 洛谷

首先前两个条件要求 l 不能是非严格后缀最值,可以分别用单调栈维护最值的位置。

而后两个限制相当于要求 l 只能在一个前缀 l\le lim 内,有了上面建出的单调栈后,只需要找到第一个不等于 a_n 的位置即可。

我们对单调栈上的元素建倍增表,这样可以快速找到 lim。再找到两个单调栈第一个 \le lim 的位置 x,y,求答案只需用 a_1\sim a_{lim} 的和减去单调栈上 x,y 之前的和即可。

可持久化操作也是容易的。

复杂度 O(m\log m)。

int m,O;

int pn[N];
int a[N],n;
int sm[N];
int f[N][21],g[N][21];
int s1[N],s2[N];

void Main() {
    cin>>m>>O;
    int lastans=0;
    int lst=0;
    fo(pid,1,m) {
        int opt,x;
        cin>>opt>>x;
        if(O) x^=lastans;
        if(opt==1) {
            a[++n]=x;
            sm[n]=add(sm[lst],x%mod);
            int t=lst;
            if(a[t]<x) {
                fd(i,20,0) if(f[t][i] && a[f[t][i]]<x) t=f[t][i];
                t=f[t][0];
            }
            f[n][0]=t;
            s1[n]=add(s1[t],x%mod);
            fo(i,1,20) f[n][i]=f[f[n][i-1]][i-1];
            t=lst;
            if(a[t]>x) {
                fd(i,20,0) if(g[t][i] && a[g[t][i]]>x) t=g[t][i];
                t=g[t][0];
            }
            g[n][0]=t;
            s2[n]=add(s2[t],x%mod);
            fo(i,1,20) g[n][i]=g[g[n][i-1]][i-1];

            t=n;
            fd(i,20,0) if(f[t][i] && a[f[t][i]]==x) t=f[t][i];
            t=f[t][0];
            int res=t;
            t=n;
            fd(i,20,0) if(g[t][i] && a[g[t][i]]==x) t=g[t][i];
            t=g[t][0];
            res=min(res,t);

            lastans=sm[res];
            t=n;
            fd(i,20,0) if(f[t][i] && f[t][i]>res) t=f[t][i];
            t=f[t][0];
            dec(lastans,s1[t]);
            t=n;
            fd(i,20,0) if(g[t][i] && g[t][i]>res) t=g[t][i];
            t=g[t][0];
            dec(lastans,s2[t]);
            cout<<lastans<<'\n';
            lst=n;
        }
        else {
            lst=pn[x];
        }
        pn[pid]=lst;
    }
}