A Simple Problem with Integers(树状数组,更新区间查询区间模板)

A Simple Problem with Integers
Time Limit: 5000MS Memory Limit: 131072K
Total Submissions: 117220 Accepted: 36444
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.

题意:

给你一段区间,区间内的点都加上某一个值,然后再求某个区间的和。

思路:(转自:http://blog.csdn.net/yukizzz/article/details/50658783

树状数组可以高效的求出连续一段元素之和或更新单个元素的值。但是无法高效的给某一个区间的所有元素同时加个值。 
不能直接用树状数组求,就处理一下。用两个树状数组维护两个数据,一个维护前 i 项和,一个维护增加的值。设:

j=1iaj=sum(bit1,i)i+sum(bit0,i)
那么 [l,r] 区间上同时加上 x 就可以表示为:

  • 对于 bit0 来说,在 l 位置上加上 x(l1) ,在 r+1 位置上加上 xr
  • 对于 bit1 来说,在 l 位置上加上 x ,在 r+1 位置上加上 x
代码:

#include <iostream>
#include <stdio.h>
#include <cstdio>
#include <cstring>
#include <algorithm>
typedef long long ll;
using namespace std;
ll bit[2][300020];
int n,q;
char ch;
int v[300020];
int lowbit(int x)
{
	return x&(-x);
}
ll sum(int i,int v)
{
	ll res=0;
	while(i>0){
		res+=bit[v][i];
		i-=lowbit(i);
	}
	return res;
}
void add(int i,int v, int t)  //t的值是0或1
{
	while(i<=n){
		bit[t][i]+=v;
		i+=lowbit(i);
	}
}
int main()
{
	ios::sync_with_stdio(false);//  不加这句话会超时
	cin>>n>>q;
	int i,j;
	int a,b,c;
	for(i=1;i<=n;i++)
	{
	cin>>v[i];
	add(i,v[i],0);
    }
for(i=0;i<q;i++)
{
	cin>>ch;
	if(ch=='C'){
		cin>>a>>b>>c;
		add(a,-c*(a-1),0);  //bit0
		add(b+1,c*b,0);
		add(a,c,1);  //bit1
		add(b+1,-c,1);
	}
	else if(ch=='Q')
	{
		cin>>a>>b;
		ll res=0;
		res += sum(b, 0) + sum(b ,1) * b;
        res -=sum(a-1, 0) +sum(a-1, 1) * (a-1);
        printf("%I64d\n",res);
	}
}
	return 0; 
} 


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值