标签:
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
题解:线段树延迟做法,就是延迟对孩子节点的操作,把前面要操作的数据记录下来,等下次必须访问孩子的时候才去做,减少递归次数。
#include <iostream> #include <cstdio> #include <cstring> #define mem(a) memset(a,0,1izeof(a)); using namespace std; long long arr[400005]; long long add[400005]; long long a[100005]; void pushUp(int k) { arr[k] = arr[k << 1] + arr[(k << 1) | 1]; } void pushDown(int k,int x) //分给左右孩子。 { if(add[k] != 0) { add[k << 1] += add[k]; add[(k << 1) | 1] += add[k]; arr[k << 1] += add[k] * (x - (x >> 1)); arr[(k << 1) | 1] += add[k] * (x >> 1); add[k] = 0; } } void segTree(int k,int l,int r) { add[k] = 0; if(l == r) { arr[k] = a[l]; return; } int mid = ( l + r) >> 1; segTree(k << 1,l,mid); segTree((k << 1) | 1,mid + 1,r); pushUp(k); } void update(int k,int l,int r,int x,int y,int c) { if(l == x && r == y) { add[k] += c; arr[k] += (r - l + 1) * c; return; } int mid = (l + r) >> 1; pushDown(k,r - l + 1); if(x > mid) { update((k << 1) | 1,mid + 1,r,x,y,c); } else if(y <= mid) { update(k << 1,l,mid,x,y,c); } else { update(k << 1,l,mid,x,mid,c); update((k << 1) | 1,mid + 1,r,mid + 1,y,c); } pushUp(k); } long long query(int k,int l,int r,int x,int y) { if(l == x && r == y) { return arr[k]; } pushDown(k,r - l + 1); int mid = (l + r) >> 1; if(x > mid) { return query((k << 1) | 1,mid + 1,r,x,y); } if(y <= mid) { return query(k << 1,l,mid,x,y); } return query(k << 1,l,mid,x,mid) + query((k << 1) | 1,mid + 1,r,mid + 1,y); } int main() { int n,m; while(scanf("%d%d",&n,&m) != EOF) { for(int i = 1;i <= n;i++) { scanf("%lld",a + i); } segTree(1,1,n); char s[3]; int l,r; for(int i = 0;i < m;i++) { scanf("%s%d%d",s,&l,&r); if('Q' == s[0]) { printf("%lld\n",query(1,1,n,l,r)); } else { long long c; scanf("%lld",&c); update(1,1,n,l,r,c); } } } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
A Simple Problem with Integers
标签:
原文地址:http://blog.csdn.net/wang2534499/article/details/47376713