POJ3468(线段树 区间修改 lazy-tag)

我的线段树真的没救了......还是多练几道吧.......

 

You have N integers, A1A2, ... , AN. You need to deal with two kinds of operations. One type of operation is to add some given number to each number in a given interval. The other is to ask for the sum of numbers in a given interval.

Input

The first line contains two numbers N and Q. 1 ≤ N,Q ≤ 100000.
The second line contains N numbers, the initial values of A1A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of AaAa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of AaAa+1, ... , Ab.

Output

You need to answer all Q commands in order. One answer in a line.

Sample Input

10 5
1 2 3 4 5 6 7 8 9 10
Q 4 4
Q 1 10
Q 2 4
C 3 6 3
Q 2 4

Sample Output

4
55
9
15

Hint

The sums may exceed the range of 32-bit integers.

 

题意:给出一个数字串,有两个操作:1. 求l-r之间的和 2.将l-r的每个数加x

 

 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 200010
#define lson root<<1
#define rson root<<1|1
using namespace std;

long long node[N<<2],lazy[N<<2];
int m,n;

void pushup(int root)
{
    node[root]=node[lson]+node[rson];
}

void pushdown(int root,int len)
{
    if(lazy[root])
    {
        lazy[lson]+=lazy[root];
        lazy[rson]+=lazy[root];
        node[lson]+=(len-(len>>1))*lazy[root];
        node[rson]+=(len>>1)*lazy[root];
        lazy[root]=0;
    }
}

void build(int l,int r,int root)
{
    lazy[root]=0;
    if(l==r)
    {
        scanf("%lld",&node[root]);
        return;
    }
    int mid=(l+r)>>1;
    build(l,mid,lson);
    build(mid+1,r,rson);
    pushup(root); 
}


void update(int left,int right,int val,int l,int r,int root)
{
    if(left<=l&&right>=r)
    {
        lazy[root]+=val;
        node[root]+=val*(r-l+1);
        return;
    }
    pushdown(root,r-l+1);
    int mid=(l+r)>>1;
    if(left<=mid)
    {
        update(left,right,val,l,mid,lson);
    }
    if(right>mid)
    {
        update(left,right,val,mid+1,r,rson);
    }
    pushup(root);
}

long long query(int left,int right,int l,int r,int root)
{
    if(left<=l&&right>=r)
    {
        return node[root];
    }
    pushdown(root,r-l+1);
    int mid=(l+r)>>1;
    long long ans=0;
    if(left<=mid)
    {
        ans+=query(left,right,l,mid,lson);
    }
    if(right>mid)
    {
        ans+=query(left,right,mid+1,r,rson);
    }
    return ans;
}

int main()
{
    scanf("%d%d",&n,&m);
    build(1,n,1);
    for(int i=1;i<=m;i++)
    {
        char s;
        int a,b,c;
        scanf(" %c",&s);
        if(s=='Q')
        {
            scanf(" %d %d",&a,&b);
            printf("%lld\n",query(a,b,1,n,1));
        }
        else
        {
            scanf(" %d %d %d",&a,&b,&c);
            update(a,b,c,1,n,1);
        }
    }
    return 0;
}

 

 

 

每天刷题,身体棒棒!

posted @ 2017-10-06 19:49  Styx-ferryman  阅读(244)  评论(0编辑  收藏  举报