[DBOI2019]持盾 题解

· · 个人记录

由于出题人实在是太菜了,出题的时候只想到了一个O(n^{\frac{5}{3}})的超劣带修莫队解法,所以数据范围小的可怜。

这题也可以用离线询问树状数组通过,这里介绍一个主席树的写法。

主席树中的第i棵线段树存的是:实施了[1,i]个战术后,每个点受到的伤害值总和。第i+1棵线段树可以把第i+1个战术攻击到的区间开新点。由于线段树一次区间查询只会访问到O(log n)个点,所以复制出来的新点也会有O(log n)个,总空间复杂度O(n log n)。

查询连续几个战术时,就可以直接主席树差分出来几个战术叠加之后对该点的增加量,然后再加上这个点的真实值就可以了。

单点修改,就直接修改某个点的真实值就行了。

代码提供者:@2016jzy

#include<iostream>
#include<cstdio>
using namespace std;
const int N=200001;
template<class type>inline void read(type &x)
{
    x=0;type f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9')
        {if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9')
        {x=(x<<3)+(x<<1)+ch-'0';ch=getchar();}
    x*=f;
    return;
}
int n,m,q,hurt[N];
int root[N],num;
struct data {
    int l,r,tag;
}t[N*40];
void build(int l,int r,int &cnt)
{
    cnt=++num;
    if(l==r)return;
    int mid=l+r>>1;
    build(l,mid,t[cnt].l);
    build(mid+1,r,t[cnt].r);
}
void update(int pre,int &cnt,int l,int r,int L,int R,int w)
{
    cnt=++num;t[cnt]=t[pre];
    if(L<=l&&r<=R)
        {t[cnt].tag+=w;return;}
    int mid=l+r>>1;
    if(L<=mid)update(t[pre].l,t[cnt].l,l,mid,L,R,w);
    if(mid+1<=R)update(t[pre].r,t[cnt].r,mid+1,r,L,R,w);
}
int query(int cnt,int l,int r,int pos)
{
    int sum=t[cnt].tag;
    if(l==r)
        return t[cnt].tag;
    int mid=l+r>>1;
    if(pos<=mid)sum+=query(t[cnt].l,l,mid,pos);
    else sum+=query(t[cnt].r,mid+1,r,pos);
    return sum;
}
int main()
{
    read(n);read(m);read(q);
    for(int i=1;i<=n;i++)
        read(hurt[i]);
    build(1,n,root[0]);
    for(int i=1;i<=m;i++) {
        int l,r,h;
        read(l);read(r);read(h);
        update(root[i-1],root[i],1,n,l,r,h);
    }
    for(int i=1;i<=q;i++) {
        int opt;
        read(opt);
        if(opt==1) {
            int x,y,z;
            read(x);read(y);read(z);
            int yy=query(root[y],1,n,z);
            int xx=query(root[x-1],1,n,z);
            printf("%d\n",yy-xx+hurt[z]);
        }
        else {
            int pos,p;
            read(pos);read(p);
            hurt[pos]=p;
        }
    }
    return 0;
}