UOJ #53.线段树区间修改


【题目描述】:

如题,已知一个数列,你需要进行下面两种操作:

1.将某区间每一个数加上x

2.求出某区间每一个数的和
【输入描述】:

第一行包含两个整数N、M,分别表示该数列数字的个数和操作的总个数。

第二行包含N个用空格分隔的整数,其中第i个数字表示数列第i项的初始值。

接下来M行每行包含3或4个整数,表示一个操作,具体如下:

操作1: 格式:1 x y k 含义:将区间[x,y]内每个数加上k

操作2: 格式:2 x y 含义:输出区间[x,y]内每个数的和
【输出描述】:

输出包含若干行整数,即为所有操作2的结果。
【样例输入】:

5 5
1 5 4 2 3
2 2 4
1 2 3 2
2 3 4
1 1 5 1
2 1 4

【样例输出】:

11
8
20

【时间限制、数据范围及描述】:

时间:1s 空间:128M

对于30%的数据:N<=8,M<=10

对于70%的数据:N<=1000,M<=10000

对于100%的数据:N<=100000,M<=100000

(数据保证在int64/long long数据范围内)

Code:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<string>
#include<stack>
#include<queue>
#include<vector>
#include<map>
using namespace std;
const int N=2000005;
long long k,c[N],sum[N],addv[N];
int n,m,i,f,x,y;
void build(int o,int l,int r){
    addv[o]=0;
    if(l==r){
        sum[o]=c[l];
    }
    else{
        int mid=(l+r)>>1;
        int lson=o<<1;
        int rson=lson|1;
        build(lson,l,mid);
        build(rson,mid+1,r);
        sum[o]=sum[lson]+sum[rson];
    }
}    
void push_down(int o,int l,int r,int mid,int lson,int rson){
    addv[lson]=addv[lson]+addv[o];
    addv[rson]=addv[rson]+addv[o];
    sum[lson]=sum[lson]+(mid-l+1)*addv[o];
    sum[rson]=sum[rson]+(r-mid)*addv[o];
    addv[o]=0;
}
void addall(int o,int l,int r,int a,int b,long long x){
    if(l>=a&&r<=b){
        addv[o]=addv[o]+x;
        sum[o]=sum[o]+(r-l+1)*x;
        return;
    }
    else{
        int mid=(l+r)>>1;
        int lson=o<<1;
        int rson=lson|1;
        if(addv[o]){
            push_down(o,l,r,mid,lson,rson);
        }
        if(a<=mid){
            addall(lson,l,mid,a,b,x);
        }
        if(b>mid){
            addall(rson,mid+1,r,a,b,x);
        }
        sum[o]=sum[lson]+sum[rson];
    }
}
long long query(int o,int l,int r,int a,int b){
    if(l>=a&&r<=b){
        return sum[o];
    }
    else{
        int mid=(l+r)>>1;
        int lson=o<<1;
        int rson=lson|1;
        long long ans=0;
        if(addv[o]){
            push_down(o,l,r,mid,lson,rson);
        }
        if(a<=mid){
            ans+=query(lson,l,mid,a,b);
        }
        if(b>mid){
            ans+=query(rson,mid+1,r,a,b);
        }
        return ans;
    }
}
int main(){
    scanf("%d%d",&n,&m);
    for(i=1;i<=n;i++){
        scanf("%lld",&c[i]);
    }
    build(1,1,n);
    for(i=1;i<=m;i++){
        scanf("%d",&f);
        switch(f){
            case 1:{
                scanf("%d%d%lld",&x,&y,&k);
                addall(1,1,n,x,y,k);
                break;
            }
            case 2:{
                scanf("%d%d",&x,&y);
                printf("%lld\n",query(1,1,n,x,y));
                break;
            }    
        }
    }
    return 0;
}
posted @ 2019-07-18 13:43  prestige  阅读(125)  评论(0编辑  收藏  举报