萌新刚学线段树0.114514毫秒,#8,9,10 WA 求调
查看原帖
萌新刚学线段树0.114514毫秒,#8,9,10 WA 求调
521118
Gyk1013楼主2023/2/26 14:09
#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;
}
2023/2/26 14:09
加载中...