样例全过,但全测试点WA

P3372 【模板】线段树 1

_Virgo_ @ 2023-03-08 18:02:44

#include<bits/stdc++.h>
#define int long long
#define N 100010
using namespace std;
//#define getchar() (strto1==strto2&&(strto2=(strto1=fsr)+fread(fsr,1,1<<15,stdin),strto1==strto2)?EOF:*strto1++)
//char fsr[1<<15],*strto1=fsr,*strto2=fsr;
inline int read()
{
    int s=0,w=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
    while(ch>='0'&&ch<='9')s=(s<<1)+(s<<3)+(ch^48),ch=getchar();
    return s*w;
}
inline void write(int x)
{
    if(x<0)putchar('-'),x=-x;
    if(x>9)write(x/10);
    putchar(x%10+'0');
}
int lefts(int x){return x<<1;}
int rights(int x){return x<<1|1;}
int n,m;
struct node
{
    int l,r;
    int sum,lazy;    
}tree[N<<5];
int a[N];
int pushup(int fa)
{
    tree[fa].sum=tree[lefts(fa)].sum+tree[rights(fa)].sum;
}
void pushdown(int fa)
{
    if(tree[fa].lazy!=0)
    {
        tree[lefts(fa)].lazy+=tree[fa].lazy;
        tree[rights(fa)].lazy+=tree[fa].lazy;
        int mid=(tree[fa].l+tree[fa].r)/2;
        tree[lefts(fa)].sum+=tree[fa].lazy*(mid-tree[lefts(fa)].l+1);
        tree[rights(fa)].sum+=tree[fa].lazy*(tree[rights(fa)].r-mid);
        tree[fa].lazy=0;
    }
}
void build(int l,int r,int fa)
{
    tree[fa].lazy=0;tree[fa].l=l;tree[fa].r=r;
    if(l==r){tree[fa].sum=a[l];return;}
    int mid=(l+r)/2;
    build(l,mid,lefts(fa));
    build(mid+1,r,rights(fa));
    pushup(fa);
}
void modify(int l,int r,int fa,int x)
{
    if(tree[fa].r<=r&&tree[fa].l>=l){tree[fa].sum+=x*(tree[fa].r-tree[fa].l|1);tree[fa].lazy+=x;return;}
    pushdown(fa);
    if(tree[lefts(fa)].r>=l)
        modify(l,r,lefts(fa),x);
    if(tree[rights(fa)].l<=r)
        modify(l,r,rights(fa),x);
    pushup(fa);
    return;
}
int query(int l,int r,int fa)
{
    if(tree[fa].l>=l && tree[fa].r<=r)
        return tree[fa].sum;
    pushdown(fa);
    int num=0;
    if(tree[lefts(fa)].r>=l)
        num+=query(l,r,lefts(fa));
    if(tree[rights(fa)].l<=r)
        num+=query(l,r,rights(fa));
    return num;
}
signed main()
{
    n=read(),m=read();
    for(int i=1;i<=n;i++)
        a[i]=read();
    build(1,n,1);
    while(m--)
    {
        int op=read(),l=read(),r=read(),x;
        if(op==1)
            x=read(),modify(l,r,1,x);
        if(op==2)
            write(query(l,r,1)),puts("");
    }
    return 0;
}

rt,求调代码


by 大眼仔Happy @ 2023-03-08 18:30:37

modify中,(tree[fa].r-tree[fa].l|1)这样写?


by Alphas @ 2023-03-08 18:39:33

r - l + 1写r - l | 1是什么鬼


by LgxTpre @ 2023-03-08 18:39:35

@Virgo |1不等于+1


by _Virgo_ @ 2023-03-08 19:53:57

@LgxTpre 艹,我是傻逼,此贴终,当时应该手滑了


|