Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 117220 | Accepted: 36444 | |
Case Time Limit: 2000MS |
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 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
题意:
给你一段区间,区间内的点都加上某一个值,然后再求某个区间的和。
思路:(转自:http://blog.csdn.net/yukizzz/article/details/50658783)
树状数组可以高效的求出连续一段元素之和或更新单个元素的值。但是无法高效的给某一个区间的所有元素同时加个值。
不能直接用树状数组求,就处理一下。用两个树状数组维护两个数据,一个维护前
i
项和,一个维护增加的值。设:
- 对于 bit0 来说,在 l 位置上加上 −x∗(l−1) ,在 r+1 位置上加上 x∗r
- 对于 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;
}