POJ3468 A Simple Problem with Integers(树状数组->改段求点)
链接:http://poj.org/problem?id=3468
题目
Time Limit:5000MS Memory Limit:131072KB
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
Hits
The sums may exceed the range of 32-bit integers.
分析
由题意知本题为树状数组的改段求点问题。
树状数组的几种模型请见:【数据结构】——树状数组的几种模型
源码
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
#include<string>
#include<sstream>
#include<cmath>
#include<set>
#include<map>
#include<vector>
#include<stack>
#include<utility>
#include<sstream>
#define mem0(x) memset(x,0,sizeof x)
#define mem1(x) memset(x,-1,sizeof x)
#define dbug cout<<"here"<<endl;
//#define LOCAL
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int INF = 0x3f3f3f3f;
const int MAXN = 1001000;
const int MOD = 1000000007;
ll treeArrA[MAXN];
ll treeArrB[MAXN];
ll n, t;
void treeUpdate(ll tmp[], ll p, ll num){
while(p <= MAXN){
tmp[p] += num;
p += p&(-p);
}
}
ll treeQuery(ll tmp[], ll p){
ll sum = 0;
while(p > 0){
sum += tmp[p];
p -= p&(-p);
}
return sum;
}
void Update(ll l, ll r, ll num){
//存储变化量
treeUpdate(treeArrA, l, num);
treeUpdate(treeArrA, r+1, -num);
//叠加前缀变化量
treeUpdate(treeArrB, l, num*(l-1));
treeUpdate(treeArrB, r+1, -num*r);
}
ll Query(ll l, ll r){
ll sumA = treeQuery(treeArrA, l-1)*(l-1) - treeQuery(treeArrB, l-1);
ll sumB = treeQuery(treeArrA, r)*r - treeQuery(treeArrB, r);
return sumB-sumA;
}
int main(){
#ifdef LOCAL
freopen("C:\\Users\\asus-z\\Desktop\\input.txt","r",stdin);
freopen("C:\\Users\\asus-z\\Desktop\\output.txt","w",stdout);
#endif
ll l,r,num;
ll tmp;
mem0(treeArrA);
mem0(treeArrB);
scanf("%I64d%I64d",&n,&t);
for(int i = 1; i <= n; ++i){
scanf("%I64d",&tmp);
Update(i, i, tmp);
}
char ch;
while(t--){
getchar();
scanf("%c", &ch);
if(ch == 'C'){
scanf("%I64d%I64d%I64d",&l,&r,&num);
Update(l, r, num);
}
else if(ch == 'Q'){
scanf("%I64d%I64d",&l,&r);
printf("%I64d\n", Query(l, r));
}
}
return 0;
}