萌新刚学线段树,样例没过求调

P3372 【模板】线段树 1

Alvin0228 @ 2024-08-10 21:24:00

#include<bits/stdc++.h>
using namespace std;
int a[400005];
struct node
{
    int val,addmark;
}segtree[400005];
void build(int root,int start,int end)
{
    segtree[root].addmark=0;
    if (start==end) segtree[root].val=a[start];
    else
    {
        int m=(start+end)/2;
        build(root*2,start,m);
        build(root*2+1,m+1,end);
        segtree[root].val=segtree[root*2].val+segtree[root*2+1].val;
    }
}
void pushdown(int root)
{
    if (segtree[root].addmark!=0)
    {
        segtree[root*2].addmark+=segtree[root].addmark;
        segtree[root*2+1].addmark+=segtree[root].addmark;
        segtree[root*2].val+=segtree[root].addmark;
        segtree[root*2+1].val+=segtree[root].addmark;
        segtree[root].addmark=0;
    }
}
int query(int root,int nstart,int nend,int qstart,int qend)
{
    if (qstart>nend||qend<nstart) return 0;
    if (qstart<=nstart&&qend>=nend) return segtree[root].val;
    pushdown(root);
    int m=(nstart+nend)/2;
    return query(root*2,nstart,m,qstart,qend)+
           query(root*2+1,m+1,nend,qstart,qend);
}
void update(int root,int nstart,int nend,int ustart,int uend,int addval)
{
    if(ustart>nend||uend<nstart) return ;
    if (ustart<=nstart&&uend>=nend)
    {
        segtree[root].addmark+=addval;
        segtree[root].val+=addval;
        return ;
    }
    pushdown(root);
    int m=(nstart+nend)/2;
    update(root*2,nstart,m,ustart,uend,addval);
    update(root*2+1,m+1,nend,ustart,uend,addval);
    segtree[root].val=segtree[root*2].val+segtree[root*2+1].val; 
}
int main ()
{
//  freopen(".in","r",stdin);
//  freopen(".out","w",stdout);
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int n,m;
    cin>>n>>m;
    for (int i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    build(1,1,n);
    for (int i=1;i<=m;i++)
    {
        int op,x,y,k;
        cin>>op;
        if (op==1)
        {
            cin>>x>>y>>k;
            update(1,1,n,x,y,k);
        }
        else
        {
            cin>>x>>y;
            cout<<query(1,1,n,x,y)<<endl;
        }
    }
    return 0;
}

by xudongyi1 @ 2024-08-10 21:26:42

@Alvin0228 你怎么写了单点改捏


by Alvin0228 @ 2024-08-10 21:46:44

@xudongyi1 哦哦哦 谢谢大佬


|