poj 3468 区间更新 整个区间加一个数和区间求和操作

http://poj.org/problem?id=3468

Description

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. 线段树里面sum值和flag值要用long long

                    2. 输入时要有一个getchar()取出回车符

#include 
#include 
#include 
using namespace std;
typedef long long LL;
const int N=100005;
LL a[N];
struct SegementTree
{
    struct Tree
    {
        int l,r;
        LL sum;
        LL flag;
    }tree[N*4];
    void push_up(int root)
    {
        tree[root].sum=tree[root<<1].sum+tree[root<<1|1].sum;
    }
    void push_down(int root)
    {
        if(tree[root].flag!=0)
        {
            tree[root<<1].flag+=tree[root].flag;
            tree[root<<1|1].flag+=tree[root].flag;//左右子树做标记
            tree[root<<1].sum+=(tree[root<<1].r-tree[root<<1].l+1)*tree[root].flag;
            tree[root<<1|1].sum+=(tree[root<<1|1].r-tree[root<<1|1].l+1)*tree[root].flag;
            tree[root].flag=0;//该节点的子树已经更新完毕,其取消标记
        }
    }
    void build(int root,int L,int R)
    {
        tree[root].l=L;
        tree[root].r=R;
        tree[root].flag=0;
        if(tree[root].l==tree[root].r)
        {
            tree[root].sum=a[L];
            return;
        }
        int mid=L+(R-L)/2;
        build(root<<1,L,mid);
        build(root<<1|1,mid+1,R);
        push_up(root);
    }
    void update(int root,int L,int R,int k)
    {
        if(L<=tree[root].l&&tree[root].r<=R)
        {
            tree[root].flag+=k;
            tree[root].sum+=(tree[root].r-tree[root].l+1)*k;
            return;
        }
        push_down(root);//本次更新到该区间,要把上次更新的区间值向其左右子树更新上次的值
        int mid=tree[root].l+(tree[root].r-tree[root].l)/2;
        if(L<=mid)
            update(root<<1,L,R,k);
        if(mid


你可能感兴趣的:(数据结构,线段树&&数组数组)