蒟蒻第一次写线段树,死循环求条

P3372 【模板】线段树 1

kind_aunt @ 2024-08-20 08:45:32

#include<bits/stdc++.h>
#define int long long 
using namespace std;
const int N=1e5+5;
int tree[N*4];
int n,m;
int a[N];
int id,l,r,val;
int lz_tag[N*4];
void build(int id,int l,int r)
{
    if(l==r)
    {
        tree[id]=a[l];
        return;
    }
    int mid=l+r>>1;
    build(id*2,l,mid);
    build(id*2+1,mid+1,r);
    tree[id]=tree[id*2]+tree[id*2+1];
}
void tag(int id,int l,int r,int k)
{
    lz_tag[id]+=k;
    tree[id]+=(r-l+1)*k;
}
void push_down(int id,int l,int r)
{
    int mid=l+r>>1;
    tag(id*2,l,mid,lz_tag[id]);
    tag(id*2+1,mid+1,r,lz_tag[id]);
    lz_tag[id]=0;
}
void update(int id,int ql,int qr,int k)
{
    if(ql>=l&&qr<=r)
    {
        tag(id,ql,qr,k);
        return;
    }
    push_down(id,l,r);
    int mid=ql+qr>>1;
    if(mid>=l) update(id*2,ql,mid,k);
    if(mid+1<=r) update(id*2+1,mid+1,qr,k);
    tree[id]=tree[id*2]+tree[id*2+1];
}
int query(int id,int ql,int qr)
{
    if(ql>=l&&qr<=r)
        return tree[id];
    int ans=0;
    push_down(id,ql,qr);
    int mid=l+r>>1;
    if(mid>=l) return ans+=query(id*2,ql,mid);
    if(mid+1<=r) return ans+=query(id*2+1,mid+1,qr);
    return ans;
}
signed main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++)
        cin>>a[i];
    build(1,1,n);
    while(m--)
    {
        cin>>id;
        if(id==1)
        {
            cin>>l>>r>>val;
            update(1,1,n,val);
        }
        else
        {
            cin>>l>>r;
            cout<<query(1,1,n)<<'\n';
        }
    }
    return 0;
}

by tzhengqing @ 2024-08-20 08:53:01

@kind_aunt query函数中int mid=l+r>>1;这一行应该是 int mid=ql+qr>>1;

莱德,需要我们


by kind_aunt @ 2024-08-20 08:57:10

@tzhengqing 感谢,已关


by kind_aunt @ 2024-08-20 08:57:36

此帖结


|