A Simple Problem with Integers
Time Limit: 5000MS Memory Limit: 131072K
Total Submissions: 106170 Accepted: 33131
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.
Source
POJ Monthly–2007.11.25, Yang Yi
其实这道题是我无聊时看到poj上有人过了这道题还跑了那么久就去看是什么题,一看样例就觉得是线段树模板题,结果我还是跑了那么久
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 100000+10;
struct Node {
ll flag,sum;
Node *ls, *rs;
}pool[N*2+5], *tail = pool, *root;
int n,q;
int aa[N];
Node *build( int lf, int rg ) {
Node *nd = ++tail;
if( rg == lf ) {
nd->sum = aa[lf];
nd->flag = 0;
} else {
int mid = (lf + rg) >> 1;
nd->ls = build( lf, mid );
nd->rs = build( mid+1, rg );
nd->sum = nd->ls->sum + nd->rs->sum;
nd->flag = 0;
}
return nd;
}
void modify( Node *nd, int lf, int rg, int L, int R, int delta ) {
if( L <= lf && rg <= R ) {
nd->flag += delta;
return;
}
int mid = (lf + rg) >> 1;
if( L <= mid ) modify( nd->ls, lf, mid, L, R, delta );
if( R > mid) modify( nd-> rs, mid+1, rg, L, R, delta );
nd->sum = nd->ls->sum + nd->rs->sum + nd->ls->flag*(mid-lf+1) + nd->rs->flag*(rg-mid);
}
ll query( Node *nd, int lf, int rg, int L, int R ) {
if( L <= lf && rg <= R ) {
return nd->sum + nd->flag * (rg - lf + 1);
}
int mid = (lf + rg) >> 1;
ll rt = (min(R,rg) - max(lf,L) + 1) * nd->flag;
if( L <= mid ) rt += query( nd->ls, lf, mid, L, R );
if( R > mid ) rt += query( nd->rs, mid+1, rg, L, R );
return rt;
}
int main() {
scanf("%d", &n);
scanf( "%d", &q );
for( int i = 1; i <= n; i++ ) scanf("%d", &aa[i]);
root = build( 1, n );
while(q--) {
char yu[5];
scanf("%s", yu);
if(yu[0] == 'C') {
int a,b,c;
scanf("%d%d%d", &a, &b, &c);
modify( root, 1, n, a, b, c );
} else {
int x,y;
scanf( "%d%d", &x, &y );
cout << query( root, 1, n, x, y ) << endl;
}
}
return 0;
}