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.
题意:
给定Q (1 ≤ Q ≤ 100,000)个数A1,A2 … AQ,,
以及可能多次进行的两个操作:
1) 对某个区间Ai … Aj的每个数都加n(n可变)
2) 求某个区间Ai … Aj的数的和
题目的数据规模容不得我们用简单的方法去解决。
本人也是第一天接触线段树,在之前AC了一道比较水的线段树后基本上能自己构建线段树
本题的解法正是利用了线段树。
值得注意的是
1.数据范围,保存数据必须用long long 或__int64保存(除了区间可以用整形,其他最后用64位)
2.只存和,会导致每次加数的时候都要更新到叶子节点,速度太慢,这是必须要避免的。
本题树节点结构:
struct CNode
{
int a ,b; //区间起点和终点
CNode * left, * right;
long long nSum; //原来的和
long long Inc; //增量c的累加
}; //本节点区间的和实际上是nSum+Inc*(R-L+1)
3.在增加时,如果要加的区间正好覆盖一个节点,则增加其节点的Inc值,不再往下走,否则要更新nSum,再将增量往下传在查询时,如果待查区间不是正好覆盖一个节点,就将节点的Inc往下带,然后将Inc代表的所有增量累加到nSum上后将Inc清0,接下来再往下查询
#include <iostream> using namespace std; #define MAXN 100010 int N,Q; __int64 num[MAXN], ans ,x; struct data { __int64 sum,inc; int l,r; }Tree[4*MAXN]; void CreateTree(int k,int l,int r) //构树 { Tree[k].l = l; Tree[k].r = r; Tree[k].inc = 0; if(l == r) Tree[k].sum = num[l]; else { int mid=(l+r)>>1; CreateTree(k+k,l,mid); CreateTree(k+k+1,mid+1,r); Tree[k].sum = Tree[k+k].sum + Tree[k+k+1].sum; } } void Add(int k,int l,int r,__int64 inc) //C操作 { if(Tree[k].l == l && Tree[k].r == r) { Tree[k].inc += inc; } else { int mid = Tree[k+k].r; Tree[k].sum += (r-l+1)*inc; if(l>mid) Add(k+k+1,l,r,inc); else if(r<=mid) Add(k+k,l,r,inc); else { Add(k+k ,l,mid,inc); Add(k+k+1 ,mid+1,r,inc); } } } void Query(int k,int l,int r,__int64 temp) { temp += Tree[k].inc; if(Tree[k].l == l &&Tree[k].r == r) { ans+= Tree[k].sum + temp * (r-l+1); } else { int mid = Tree[k+k].r; if(l>mid) Query(k+k+1,l,r,temp); else if(r<=mid) Query(k+k,l,r,temp); else { Query(k+k ,l,mid,temp); Query(k+k+1 ,mid+1,r,temp); } } } int main() { int i,j; char ch; while(scanf("%d%d",&N,&Q)!=EOF) { for(i=1;i<=N;i++) scanf("%I64d",&num[i]); CreateTree(1,1,N); while(Q--) { getchar(); scanf("%c %d %d",&ch,&i,&j); if(ch=='Q') { ans = 0; Query(1,i,j,0); printf("%I64d\n",ans); } else { scanf("%I64d",&x); Add(1,i,j,x); } } } }