萌新wa求调

P3372 【模板】线段树 1

I_Was_Spasmodic @ 2024-03-07 19:33:55

#include<bits/stdc++.h>
using namespace std;
const int M=100005;
int n,m;
int a[M];
struct Tree{
    int l,r,add;
    long long d;
}t[M*4];
void build(int p,int l,int r)
{
    t[p].l=l;
    t[p].r=r;
    t[p].add=0;
    if(l==r)
    {
        t[p].d=a[l];
        return;
    }
    int mid=(l+r)/2;
    build(p*2,l,mid);
    build(p*2+1,mid+1,r);
    t[p].d=t[p*2].d+t[p*2+1].d;
}
void check(int p)
{
    if(t[p].add)
    {
        t[p*2].add+=t[p].add;
        t[p*2+1].add+=t[p].add;
        t[p*2].d+=(t[p*2].r-t[p*2].l+1)*t[p].add;
        t[p*2+1].d+=(t[p*2+1].r-t[p*2+1].l+1)*t[p].add;
        t[p].add=0;
    }
}
void change(int p,int l,int r,int add)
{
//  cout<<p<<'  ';
//  if(p>n*4)return;
    if(l<=t[p].l and r>=t[p].r)
    {
        t[p].add+=add;
        t[p].d+=(t[p].r-t[p].l+1)*add;
        return;
    }
    if(t[p].l==t[p].r)
    {
        t[p].d+=add;
        return;
    }
    check(p);
    int mid=(t[p].l+t[p].r)/2;
    if(mid>=l)change(p*2,l,r,add);
    if(mid<r)change(p*2+1,l,r,add);
    t[p].d=t[p*2].d+t[p*2+1].d;
}
long long ask(int p,int l,int r)
{
//  if(p>n*4)return 0;
    if(l<=t[p].l and r>=t[p].r)return t[p].d;
    if(t[p].l==t[p].r)return t[p].d;
    check(p);
    int mid=(t[p].l+t[p].r)/2;
    long long rt=0;
    if(mid>=l)rt+=ask(p*2,l,r);
    if(mid< r)rt+=ask(p*2+1,l,r);
    printf("%d[%d , %d] : %d\n",p,t[p].l,t[p].r,rt);
    return rt;
}
int main()
{
    cin>>n>>m;
    for(int i=0;i<n;i++)cin>>a[i];
    while(m--)
    {
        int tp;
        cin>>tp;
        if(tp==1)
        {
            int x,y,k;
            cin>>x>>y>>k;
            change(1,x,y,k);
        }
        else 
        {
            int x,y;
            cin>>x>>y;
            cout<<ask(1,x,y)<<'\n';
        }
    }
}

by I_Was_Spasmodic @ 2024-03-07 19:34:43

有一个忘注释了,就当没看见()


by fsdgakjl @ 2024-03-07 19:38:31

@I_Was_Spasmodic

你的 build 呢。


by I_Was_Spasmodic @ 2024-03-07 19:41:17

@fsdgakjl 我草我是若至()


by Catalan1906 @ 2024-03-07 19:47:55

@I_Was_Spasmodic 笑死我了


by HeYilin @ 2024-03-07 19:51:42


by Gerogefather @ 2024-03-07 21:42:22

666


by Gerogefather @ 2024-03-07 21:43:07

@I_Was_Spasmodic 666


|