题目链接:http://poj.org/problem?id=3468
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
The sums may exceed the range of 32-bit integers.
ti'm题目大意:给你n个数,m个操作,
每个操作有两种情况,输入Q时,输入两个数,a,b,求a~b的值的和
输入C时,输入三个数,a,b,x,让a~b区间的每个数都加上x。
区间修改+qu'j区间查询,模板
原理:
区间修改,区间查询:
引入一个函数:sigma(a,i)表示a数组的前i项和
引入一个差分数组,c[i]=a[i]-a[i-1];
因此:a[i]=sigma(c,i);
a[i]=c[1]+c[2]+c[3]+...+c[k];
因此:
sum(1~k)=a[1]+a[2]+a[3]+a[4]+...+a[k];
=c[1]+( c[1]+c[2] )+( c[1]+c[2]+c[3] )+...+(c[1]+c[2]+c[3]+...+c[k]).
=k*c[1]+(k-1)*c[2]+(k-2)*c[3]+...+ 1*c[k];
合并:
sum(1~k)=sigma( (k-i+1)c[i] );//这个就是求和,1~k项的和,中间的是通项
将它分开:
sum(1~k)=sigma( (k+1)*c[i] )-sigma( i*c[i] );
因此分成两个数组,建立两个树状数组,
分别为:
tree1[i]=c[i];
/*-------*/
tree2[i]=i*c[i]
用第一个减去第二个就是区间查询的结果了
计算的时候:
ans=(k+1)*tree1[i]-tree2[i];
ac:
#include
#include
#include
//#include
补充一下,这个题也可以用线段树解决,虽然感觉有点麻烦:
ac:
#include
#include
#include
//#include