BZOJ3212 Pku3468 A Simple Problem with Integers

线段树

题目传送门

全裸线段树

代码:

#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 100005
#define F inline
using namespace std;
typedef long long LL;
struct tree{ int l,r,f; LL x; }t[N<<2];
int n,m,a[N];
F char readc(){
    static char buf[100000],*l=buf,*r=buf;
    if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
    return l==r?EOF:*l++;
}
F int _read(){
    int x=0,f=1; char ch=readc();
    while (!isdigit(ch)&&!isupper(ch)){ if (ch=='-') f=-1; ch=readc(); }
    if (isupper(ch)) return ch;
    while (isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=readc();
    return x*f;
}
F void writec(LL x){
    if (x<0) putchar('-'),x=-x;
    if (x>9) writec(x/10); putchar(x%10+48);
}
F void _write(LL x){ writec(x),puts(""); }
F void pshd(int x){
    t[x<<1].x+=1ll*t[x].f*(t[x<<1].r-t[x<<1].l+1);
    t[x<<1|1].x+=1ll*t[x].f*(t[x<<1|1].r-t[x<<1|1].l+1);
    t[x<<1].f+=t[x].f,t[x<<1|1].f+=t[x].f,t[x].f=0;
}
void build(int x,int l,int r){
    t[x]=(tree){l,r,0,a[l]};
    if (l==r) return; int mid=l+r>>1;
    build(x<<1,l,mid),build(x<<1|1,mid+1,r);
    t[x].x=t[x<<1].x+t[x<<1|1].x;
}
void mdfy(int x,int l,int r,int w){
    if (t[x].l>r||t[x].r<l) return;
    if (t[x].l>=l&&t[x].r<=r){
        t[x].x+=1ll*(t[x].r-t[x].l+1)*w;
        t[x].f+=w; return;
    }
    if (t[x].f) pshd(x);
    mdfy(x<<1,l,r,w),mdfy(x<<1|1,l,r,w);
    t[x].x=t[x<<1].x+t[x<<1|1].x;
}
LL srch(int x,int l,int r){
    if (t[x].l>r||t[x].r<l) return 0;
    if (t[x].l>=l&&t[x].r<=r) return t[x].x;
    if (t[x].f) pshd(x);
    return srch(x<<1,l,r)+srch(x<<1|1,l,r);
}
int main(){
    n=_read(),m=_read();
    for (int i=1;i<=n;i++) a[i]=_read();
    for (build(1,1,n);m;m--){
        int f=_read(),l=_read(),r=_read(),x;
        if (f=='Q') _write(srch(1,l,r));
        else x=_read(),mdfy(1,l,r,x);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/a1799342217/article/details/80890397
今日推荐