A Simple Problem with Integers——区间查询去区间修改模板题

Posted j666

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了A Simple Problem with Integers——区间查询去区间修改模板题相关的知识,希望对你有一定的参考价值。

题目链接

题意:

C a b c  【a,b】区间都加c

Q a b   查询【a,b】的区间和

题解:

区间修改+区间查询 模板题

代码:

技术图片
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<vector>
#include<map>
using namespace std;
typedef long long ll;
const int maxn = 1e5+5;
struct node

    int l,r;
    ll sum,lazy;
    void update(ll x)
    
        sum+=1ll*(r-l+1)*x;
        lazy+=x;
    
tree[maxn<<2];
int n,m,a[maxn];
void push_up(int x)

    tree[x].sum=tree[x<<1].sum+tree[x<<1|1].sum;

void push_down(int x)

    ll lazyval=tree[x].lazy;
    if(lazyval)
    
        tree[x<<1].update(lazyval);
        tree[x<<1|1].update(lazyval);
        tree[x].lazy=0;
    

void build(int x,int l,int r)

    tree[x].l=l,tree[x].r=r;
    tree[x].lazy=tree[x].sum=0;
    if(l==r)tree[x].sum=a[l];
    else
    
        int mid=(l+r)>>1;
        build(x<<1,l,mid);
        build(x<<1|1,mid+1,r);
        push_up(x);
    


void update(int x,int l,int r,ll val)

    int L=tree[x].l,R=tree[x].r;
    if(l<=L && R<=r)tree[x].update(val);
    else
    
        push_down(x);
        int mid=(L+R)>>1;
        if(mid>=l)update(x<<1,l,r,val);
        if(mid<r)update(x<<1|1,l,r,val);
        push_up(x);
    

ll query(int x,int l,int r)

    
    int L=tree[x].l,R=tree[x].r;
    if(l<=L && R<=r)return tree[x].sum;
    else
    
        ll ans=0;
        push_down(x);
        int mid=(L+R)>>1;
        if(mid>=l)ans+=query(x<<1,l,r);
        if(mid<r)ans+=query(x<<1|1,l,r);
        push_up(x);
        return ans;
    
    


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--)
    
        char op;
        cin>>op;
        if(op==C)
        
            int a,b;
            ll c;
            scanf("%d%d%lld",&a,&b,&c);
            update(1,a,b,c);
        
        else
        
            int a,b;
            scanf("%d%d",&a,&b);
            printf("%lld\n",query(1,a,b));
        
    

    return 0;
View Code

 

以上是关于A Simple Problem with Integers——区间查询去区间修改模板题的主要内容,如果未能解决你的问题,请参考以下文章

POJ3468A Simple Problem with Integers

线段树专题 POJ3468 A Simple Problem with Integers

A Simple Problem with Integers

A Simple Problem with Integers

POJ 3468 A Simple Problem with Integers

POJ3468 A Simple Problem with Integers