一种数据结构思想:维护操作对操作贡献

· · 个人记录

P5524 [Ynoi2012] NOIP2015 充满了希望

考虑只有 2 和 3 操作。

有结论是:一个 3 操作对询问的贡献,要么为其上次被 2 操作赋的值,要么为 0。这是显然的。

这启发我们维护每个 3 操作上次的 2 操作。开线段树,区间赋值单点查询,对每个 3 操作,查询 x 位置上次被哪个 2 操作即可。考虑加上 1 操作,就是交换两个位置的上次 2 操作。

如何回答询问?对每个询问,统计其区间内的 3 操作,一个 3 操作,若其上次 2 操作的时间在区间内,则贡献为 2 操作的 z,否则为 0。于是直接二维数点即可,总的时间复杂度为 \mathcal{O}(m\log n+(m+q)\log(m+q)),在 n,m,q 同阶下为 \mathcal{O}(n\log n)。

代码:

#include<bits/stdc++.h>
using namespace std;
struct opti
{
    bool op;
    int pos,x,v,id;
    bool operator<(opti b)const{return pos!=b.pos?pos<b.pos:op<b.op;}
}opt[3000001];
int n,m,q,g[4000001],tg[4000001],opcnt,mf[1000001];
long long c[1000001],ans[1000001];
char xch,xB[1<<22],*xS=xB,*xTT=xB;
#define getc (xS==xTT&&(xTT=(xS=xB)+fread(xB,1,1<<22,stdin),xS==xTT)?0:*xS++)
int read()
{
    int s=0;
    char ch=getc;
    while(ch<'0'||ch>'9')ch=getc;
    while(ch>='0'&&ch<='9')
    {
        s=s*10+ch-48;
        ch=getc;
    }
    return s;
}
void pushdown(int p)
{
    g[p<<1]=g[p<<1|1]=tg[p<<1]=tg[p<<1|1]=tg[p];
    tg[p]=0;
}
void updateg(int p,int cl,int cr,int x,int y,int k)
{
    if(x<=cl&&cr<=y)
    {
        g[p]=tg[p]=k;
        return;
    }
    int mid=cl+cr>>1;
    if(tg[p])pushdown(p);
    if(mid>=x)updateg(p<<1,cl,mid,x,y,k);
    if(mid<y)updateg(p<<1|1,mid+1,cr,x,y,k);
}
int queryg(int p,int cl,int cr,int x)
{
    if(cl==cr)return g[p];
    int mid=cl+cr>>1;
    if(tg[p])pushdown(p);
    return mid>=x?queryg(p<<1,cl,mid,x):queryg(p<<1|1,mid+1,cr,x);
}
void update(int x,int y){for(;x<=m;x+=x&-x)c[x]+=y;}
long long query(int x)
{
    long long res=0;
    for(;x;x-=x&-x)res+=c[x];
    return res;
}
signed main()
{
    n=read();
    m=read();
    q=read();
    for(int i=1,op,x,y,z;i<=m;i++)
    {
        op=read();
        x=read();
        if(op==1)
        {
            y=read();
            int gx=queryg(1,1,n,x),gy=queryg(1,1,n,y);
            updateg(1,1,n,x,x,gy);
            updateg(1,1,n,y,y,gx);
        }
        else if(op==2)
        {
            y=read();
            z=read();
            mf[i]=z;
            updateg(1,1,n,x,y,i);
        }
        else
        {
            int qr=queryg(1,1,n,x);
            opt[++opcnt]=opti{0,i,qr,mf[qr]};
        }
    }
    for(int i=1,x,y;i<=q;i++)
    {
        x=read();
        y=read();
        opt[++opcnt]=opti{1,x-1,x,-1,i};
        opt[++opcnt]=opti{1,y,x,1,i};
    }
    sort(opt+1,opt+opcnt+1);
    for(int i=1;i<=opcnt;i++)
    {
        if(opt[i].op)ans[opt[i].id]+=(query(m)-query(opt[i].x-1))*opt[i].v;
        else if(opt[i].x)update(opt[i].x,opt[i].v);
    }
    for(int i=1;i<=q;i++)printf("%lld\n",ans[i]);
    return 0;
}