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 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.

树状数组的前缀和推倒过程见算法

竞赛进阶指南 第200页

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<stack>
#include<cstdlib>
#include<cctype>
using namespace std;
#define ll long long
typedef pair<int,int>P;
const int len=1e5+5;
const int mod=1e4+7;
int n,q;
ll sum[len],arr[len];//sum[i],n个数的前缀和 
ll c[2][len];//树状数组维护的前缀和 
int lowbit(int i)
{
	return i&(-i);
}
ll ask(int k,int i)
{
	ll ans=0;
	for(;i;i-=lowbit(i))ans+=c[k][i];
	return ans;
}
void add(int k,int i,ll v)
{
	for(;i<=n;i+=lowbit(i))
		c[k][i]+=v;
}
int main()
{
	while(cin>>n>>q)
	{
		memset(sum,0,sizeof(sum));
		memset(c,0,sizeof(c));
		for(int i=1;i<=n;++i)
		{
			scanf("%lld",arr+i);
			sum[i]=sum[i-1]+arr[i];
		}
		char str[3];
		ll l,r,w;
		while(q--)
		{
			scanf("%s",str);
			if(str[0]=='C')
			{
				scanf("%lld%lld%lld",&l,&r,&w);
				add(0,l,w);
				add(0,r+1,-w);
				add(1,l,l*w);
				add(1,r+1,-(r+1)*w);
			}
			else
			{
				scanf("%lld%lld",&l,&r);
				ll ans=sum[r]+(r+1)*ask(0,r+1)-ask(1,r+1);//求出r的前缀和 
				ans-=sum[l-1]+l*ask(0,l-1)-ask(1,l-1);//减去l-1的前缀和 
				printf("%lld\n",ans);
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/hutwuguangrong/article/details/81154563