萌新刚学线段树0.114514毫秒,#8,9,10 WA 求调

P3372 【模板】线段树 1

Gyk1013 @ 2023-02-26 14:09:44

#include<bits/stdc++.h>
#define N 100005
#define ll long long
using namespace std;
int a[N];
struct node{
    int value,lazy;
    int left,right;
}tree[N*4];
void build(int root,int l,int r){
    tree[root].left=l;
    tree[root].right=r;
    if(l==r){
        tree[root].value=a[l];
        return;
    }
    int mid=(l+r)/2;
    build(root*2,l,mid);
    build(root*2+1,mid+1,r);
    tree[root].value=tree[root*2].value+tree[root*2+1].value;
}
void spread(int p){
    int la=tree[p].lazy;
    if(la!=0){
        tree[p*2].value+=la*(tree[p*2].right-tree[p*2].left+1);
        tree[p*2].lazy+=la;
        tree[p*2+1].value+=la*(tree[p*2+1].right-tree[p*2+1].left+1);
        tree[p*2+1].lazy+=la;
        tree[p].lazy=0;
    }
}
ll query(int root,int l,int r){
    if(tree[root].left>=l&&tree[root].right<=r) return tree[root].value;
    int mid=(tree[root].left+tree[root].right)/2;
    ll ans=0;
    spread(root);
    if(l<=mid) ans+=query(root*2,l,r);
    if(r>mid) ans+=query(root*2+1,l,r);
    return ans;
}

void update(int root,int l,int r,int v){
    if(l<=tree[root].left&&r>=tree[root].right){
        tree[root].value+=v*(tree[root].right-tree[root].left+1);
        tree[root].lazy+=v;
        return;
    }
    spread(root);
    int mid=(tree[root].left+tree[root].right)/2;
    if(l<=mid) update(root*2,l,r,v);
    if(r>mid) update(root*2+1,l,r,v);
    tree[root].value=tree[root*2].value+tree[root*2+1].value;
}
int main(){
    int n,m;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++) scanf("%d",&a[i]);
    build(1,1,n);
    while(m--){
        int op,l,r,k;
        scanf("%d",&op);
        if(op==1) scanf("%d%d%d",&l,&r,&k),update(1,l,r,k);
        else scanf("%d%d",&l,&r),printf("%lld\n",query(1,l,r));
    }
    return 0;
}

by Untitled10032 @ 2023-02-26 14:15:12

struct node 里的 value 可能要开 long long


by 07kzs @ 2023-02-26 14:15:54

@Gyk1013 没开long long

struct node{
    ll value,lazy;
    ll left,right;
}tree[N*4];

by Gyk1013 @ 2023-02-26 14:21:41

@Untitled10032 @07kzs 感谢两位大佬


|