POJ3468-A Simple Problem with Integers(線段樹 區間更新 加和)

題目鏈接

Description

You have N integers, A1, A2, ... , 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 A
1, A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of A
a, Aa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of A
a, Aa+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.


題意

N個數,Q個操作,訪問區間和,修改區間的值,給區間每一個數增大某個值

思路

線段樹lazy標記,增加的是區間內每一個數,lazy需要寫成+= 。

lazy和w需要用long long,乘法的地方需要1ll* ,int會爆。


#include <iostream>
#include <cstdio>
#define  ll long long
using namespace std;

struct node
{
    int l,r;
    ll w,lazy;
};

node tree[100010*4];
ll init[100010*4];
void build(int k,int l,int r)
{
    tree[k].l = l; tree[k].r = r; tree[k].lazy = 0;
    if(l==r){
        tree[k].w = init[l];
        return;
    }
    int mid = (l + r)/2;
    build(k*2,l,mid);
    build(k*2+1,mid+1,r);
    tree[k].w = tree[k*2].w + tree[k*2+1].w;
}

void pushdown(int k)
{
    tree[k*2].lazy += tree[k].lazy;
    tree[k*2+1].lazy += tree[k].lazy;
    int len = tree[k].r - tree[k].l + 1;
    tree[k*2].w += (len-len/2)*tree[k].lazy;
    tree[k*2+1].w += (len/2)*tree[k].lazy;
    tree[k].lazy = 0;
}

void update(int k,int l,int r,int v)// 區間修改,l-r區間修改爲增加v
{
    if(l>tree[k].r||r<tree[k].l) return;
    if(l<=tree[k].l&&tree[k].r<=r){
        tree[k].lazy += v; //加標記
        tree[k].w += (tree[k].r - tree[k].l + 1)*v; 
        return;
    }
    if(tree[k].lazy) pushdown(k);
    update(k*2,l,r,v);
    update(k*2+1,l,r,v);
    tree[k].w = tree[k*2].w + tree[k*2+1].w;
}

ll query(int k,int l,int r)
{
    if(l>tree[k].r||r<tree[k].l) return 0;
    if(tree[k].lazy) pushdown(k);
    if(l<=tree[k].l&&tree[k].r<=r) return tree[k].w;
    return query(k*2,l,r) + query(k*2+1,l,r);
}

int main()
{
    int N,T,a,b;
    int c;
    scanf("%d%d",&N,&T);
    for(int i=1;i<=N;i++){
        scanf("%lld",&init[i]);
    }
    build(1,1,N);
    for(int i=1;i<=T;i++){
        char ch; scanf(" %c",&ch);
        if(ch=='Q'){
            scanf("%d%d",&a,&b);
            printf("%lld\n",query(1,a,b));
        }
        else if(ch=='C'){
            scanf("%d%d%d",&a,&b,&c);
            update(1,a,b,c);
        }
    }
}

 

發佈了62 篇原創文章 · 獲贊 29 · 訪問量 4751
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章