poj3468--A Simple Problem with Integers(树状数组解法)

A Simple Problem with Integers
Time Limit: 5000MS Memory Limit: 131072K
Total Submissions: 59247 Accepted: 18032
Case Time Limit: 2000MS

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.

Source

POJ Monthly--2007.11.25, Yang Yi
出自http://kenby.iteye.com/blog/962159
给出n个数,m次操作,Q x y 询问[x,y]的和,C x y b 在[x,y]中的每个数均加b
首先记录下由1到i的初始值(记录到a数组中),Q x y 的和  sum = a[y] - a[x-1] + S(操作改变的值) , 定义一个数组k[],k[i]表示为由i到n的所有值均加k[i],那么C x y b 表示为 :k[x]+b,k[y+1]-b ;S =  Sy - S(x-1) ;Si = a[1]*i+a[2]*(i-1)+。。a[i]*1 ----->>>  Si = (i+1)*(k[1]+k[2]+k[3]。。k[i]) - (k[1]*1+k[2]*2+k[3]*3。。k[i]*i) ;
由此转化为了要求k[1]累加到k[i]的和,k[1]*1累加到k[i]*i的和,使用树状数组可以log(n)的时间求到结果
#include <cstdio>
#include <cstring>
#define LL long long int
LL a[100010] , b[100010] , c[100010] ;
int lowbit(int x)
{
    return x & -x;
}
void add(LL *s,int i,int x,int n)
{
    while( i <= n )
    {
        s[i] += x ;
        i += lowbit(i) ;
    }
}
LL get(LL *s,int i)
{
    LL sum = 0;
    while( i )
    {
        sum += s[i] ;
        i -= lowbit(i) ;
    }
    return sum;
}
LL f(int i)
{
    LL sum = a[i] ;
    sum +=  ( (i+1)*get(b,i) - get(c,i) ) ;
    return sum ;
}
int main()
{
    int i , n , m , l , r ;
    LL x , sum ;
    char ch ;
    memset(a,0,sizeof(a));
    memset(b,0,sizeof(b));
    memset(c,0,sizeof(c));
    scanf("%d %d", &n, &m);
    for(i = 1 ; i <= n ; i++)
    {
        scanf("%lld", &x);
        a[i] += a[i-1] + x ;
    }
    while(m--)
    {
        getchar();
        scanf("%c", &ch);
        if(ch == 'Q')
        {
            scanf("%d %d", &l, &r);
            sum = f(r) - f(l-1) ;
            printf("%lld\n", sum) ;
        }
        else
        {
            scanf("%d %d %d", &l, &r, &x);
            add(b,l,x,n) ;
            add(b,r+1,-x,n);
            add(c,l, x*l ,n);
            add(c,r+1, -(x*(r+1)),n);
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值