1. 程式人生 > >POJ 3468 A Simple Problem with Integers 區間更新模板題

POJ 3468 A Simple Problem with Integers 區間更新模板題

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

區間更新的模板題

程式碼如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn=100005;
int n,q;
long long int tree[maxn<<2];
//懶惰標記
long long int lazy[maxn<<2];
int a[maxn];
void pushup (int re)
{
    tree[re]=tree[re<<1]+tree[re<<1|1];
}
//下推懶惰標記
void pushdown (int re,int ln,int rn)
{
    if(lazy[re])
    {
        lazy[re<<1]+=lazy[re];
        lazy[re<<1|1]+=lazy[re];
        tree[re<<1]+=lazy[re]*ln;
        tree[re<<1|1]+=lazy[re]*rn;
        lazy[re]=0;
    }
}
void build (int l,int r,int re)
{
    if(l==r)
    {
        tree[re]=a[l];
        return;
    }
    int mid=(l+r)>>1;
    build (l,mid,re<<1);
    build (mid+1,r,re<<1|1);
    pushup (re);
}
//區間更新
void quee (int left,int right,int data,int l,int r,int re)
{
    if(l>=left&&r<=right)
    {
        lazy[re]+=data;
        tree[re]+=data*(r-l+1);
        return;
    }
    int mid=(l+r)>>1;
    pushdown (re,mid-l+1,r-mid);
    if(mid>=left)
       quee (left,right,data,l,mid,re<<1);
    if(mid<right)
       quee (left,right,data,mid+1,r,re<<1|1);
    pushup (re);
}
//區間查詢
long long int query (int left,int right,int l,int r,int re)
{
    if(left<=l&&right>=r)
    {
        return tree[re];
    }
    int mid=(l+r)>>1;
    pushdown (re,mid-l+1,r-mid);
    long long int ans=0;
    if(mid>=left)
        ans+=query (left,right,l,mid,re<<1);
    if(mid<right)
        ans+=query (left,right,mid+1,r,re<<1|1);
    return ans;
}
int main()
{
    while(scanf("%d%d",&n,&q)!=EOF)
    {
     memset (lazy,0,sizeof(lazy));
    for (int i=1;i<=n;i++)
        scanf("%d",&a[i]);
    build (1,n,1);
    for (int i=1;i<=q;i++)
    {
        char s[5];
        scanf("%s",s);
        if(s[0]=='Q')
        {
            int x,y;
            scanf("%d%d",&x,&y);
           printf("%I64d\n",query (x,y,1,n,1));
        }
        else
        {
           int x,y,d;
           scanf("%d%d%d",&x,&y,&d);
           quee(x,y,d,1,n,1);
        }
    }
    }
    return 0;
}