POJ 3468 A Simple Problem with Integers (+ range segment tree modify, query interval)

Meaning of the questions:
given a sequence, both.
QLR: Query [L, R] and the interval of
CLRX: the [L, R] of each section increases the number of X

Ideas:
segment tree template question: interval + modify the query interval
lazy : lazy mark
special: increase push_down ()

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#define ll long long

using namespace std;

const int maxn=100005;
struct node
{
    ll l,r,sum,lazy;
    void update(ll k)
    {
        sum+=(r-l+1)*k;
        lazy+=k;
    }
}tree[4*maxn];
ll n,m,a[maxn];

void push_up(ll id)
{
    tree[id].sum=tree[id*2].sum+tree[id*2+1].sum;
}
void push_down(ll id)
{
    if(tree[id].lazy)
    {
        tree[id*2].update(tree[id].lazy);
        tree[id*2+1].update(tree[id].lazy);
        tree[id].lazy=0;
    }
}
void build(ll id,ll l,ll r)
{
    tree[id].l=l;
    tree[id].r=r;
    if(l==r)
    {
        tree[id].sum=a[l];
        return;
    }
    ll mid=l+(r-l)/2;
    build(id*2,l,mid);
    build(id*2+1,mid+1,r);
    push_up(id);
}
void update(ll id,ll l,ll r,ll k)
{
    ll L=tree[id].l,R=tree[id].r;
    if(l<=L&&R<=r)
    {
        tree[id].update(k);
        return;
    }
    if(l>R||r<L)
        return;
    push_down(id);
    if(tree[id*2].r>=L)
    {
        update(id*2,l,r,k);
    }
    if(tree[id*2+1].l<=R)
    {
        update(id*2+1,l,r,k);
    }
    push_up(id);
}
ll query(ll id,ll l,ll r)
{
    ll L=tree[id].l,R=tree[id].r;
    if(l<=L&&R<=r)
    {
        return tree[id].sum;
    }
    if(l>R||r<L)
        return 0;
    push_down(id);
    ll ans=0;
    if(tree[id*2].r>=L)
    {
        ans+=query(id*2,l,r);
    }
    if(tree[id*2+1].l<=R)
    {
        ans+=query(id*2+1,l,r);
    }
    return ans;
}
int main()
{
    scanf("%lld%lld",&n,&m);
    for(ll i=1;i<=n;i++)
        scanf("%lld",&a[i]);
    char s[10];
    ll x,y,k;
    build(1,1,n);
    while(m--)
    {
        scanf("%s",&s);
        if(s[0]=='Q')
        {
            scanf("%lld%lld",&x,&y);
            printf("%lld\n",query(1,x,y));
        }
        else if(s[0]=='C')
        {
            scanf("%lld%lld%lld",&x,&y,&k);
            update(1,x,y,k);
        }
    }
    return 0;
}
Published 19 original articles · won praise 0 · Views 173

Guess you like

Origin blog.csdn.net/qq_43032263/article/details/104425870