poj 3468 A Simple Problem with Integers
A Simple Problem with Integers
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 70937 | Accepted: 21874 | |
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
The sums may exceed the range of 32-bit integers.
线段树成段更新,成段求和。
要注意的就是可能会超过int,要用long long
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <string> 5 #include <iomanip> 6 using namespace std; 7 #define maxn 100010 8 #define lson l, m, rt<<1 9 #define rson m+1, r, rt<<1|1 10 long long sum[maxn<<2], col[maxn<<2]; 11 int N, Q; 12 void PushUP(int rt){ 13 sum[rt] = sum[rt<<1] + sum[rt<<1|1]; 14 } 15 void PushDown(int rt, int len){ 16 if(col[rt]){ 17 col[rt<<1] += col[rt]; 18 col[rt<<1|1] += col[rt]; 19 sum[rt<<1] += col[rt]*(len-(len>>1)); 20 sum[rt<<1|1] += col[rt]*(len>>1); 21 col[rt] = 0; 22 } 23 } 24 void build(int l, int r, int rt){ 25 col[rt] = 0; 26 if(l == r){ 27 scanf("%lld", &sum[rt]); 28 return; 29 } 30 int m = (r+l)>>1; 31 build(lson); 32 build(rson); 33 PushUP(rt); 34 } 35 void update(int L, int R, int c, int l, int r, int rt){ 36 if(L <= l && r <= R){ 37 col[rt] += c; 38 sum[rt] += c*(r-l+1); 39 return; 40 } 41 PushDown(rt, r-l+1); 42 int m = (l+r)>>1; 43 if(L <= m) update(L, R, c, lson); 44 if(R > m) update(L, R, c, rson); 45 PushUP(rt); 46 } 47 long long query(int L, int R, int l, int r, int rt){ 48 if(L <= l && r <= R){ 49 return sum[rt]; 50 } 51 PushDown(rt, r-l+1); 52 int m = (l+r)>>1; 53 long long ret = 0; 54 if(L <= m) ret += query(L, R, lson); 55 if(m < R) ret += query(L, R, rson); 56 return ret; 57 } 58 int main(){ 59 while(~scanf("%d%d", &N, &Q)){ 60 build(1, N, 1); 61 while(Q--){ 62 char ch; cin>>ch; 63 int a, b, c; 64 if(ch == 'Q'){ 65 scanf("%d%d", &a, &b); 66 printf("%lld\n",query(a,b,1,N,1)); 67 } 68 else if(ch == 'C'){ 69 scanf("%d%d%d", &a, &b, &c); 70 update(a, b, c, 1, N, 1); 71 } 72 } 73 } 74 75 return 0; 76 }