A Simple Problem with Integers
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 138575 | Accepted: 42915 | |
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
线段树练习、AC代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
#define lson rt<<1,left,m
#define rson rt<<1|1,m+1,right
const int maxn = 1e5 + 10;
ll sum[maxn<<2],add[maxn<<2]; // sum区间和 add延迟标记数组
struct node{
int left,right;
int mid(){
return (left+right)>>1;
}
}tree[maxn<<2];
void PushUp(int rt){ //向上更新
sum[rt] = sum[rt<<1] + sum[rt<<1|1];
}
void PushDown(int rt,int m){
if(add[rt]){
add[rt<<1] += add[rt];
add[rt<<1|1] += add[rt];
sum[rt<<1] += add[rt]*(m-(m>>1));
sum[rt<<1|1] += add[rt]*(m>>1);
add[rt] = 0;
}
}
void BuildTree(int rt,int left,int right){
tree[rt].left = left;
tree[rt].right = right;
add[rt] = 0;
if( left == right){
scanf("%lld",&sum[rt]);
return ;
}
int m = tree[rt].mid();
BuildTree(lson);
BuildTree(rson);
PushUp(rt);
}
void Update(int c,int left,int right,int rt){
if(tree[rt].left == left && tree[rt].right == right){
add[rt] += c;
sum[rt] += (ll)c*(right-left+1);
return;
}
if(tree[rt].left == tree[rt].right ) return ;
PushDown(rt,tree[rt].right-tree[rt].left+1);
int m = tree[rt].mid();
if(right <= m) Update(c,left,right,rt<<1);
else if(left > m ) Update(c,left,right,rt<<1|1);
else{
Update(c,left,m,rt<<1);
Update(c,m+1,right,rt<<1|1);
}
PushUp(rt);
}
ll Query(int rt,int left,int right){
if(tree[rt].left == left && tree[rt].right == right){
return sum[rt];
}
PushDown(rt,tree[rt].right-tree[rt].left+1);
int m = tree[rt].mid();
ll ans = 0;
if(right <= m ) ans+=Query(rt<<1,left,right);
else if(left > m) ans+=Query(rt<<1|1,left,right);
else{
ans+=Query(rt<<1,left,m);
ans+=Query(rt<<1|1,m+1,right);
}
return ans;
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m)){
BuildTree(1,1,n);
char ch[2];
int a,b,c;
while(m--){
scanf("%s",ch);
if(ch[0] == 'Q'){
scanf("%d%d",&a,&b);
printf("%lld\n",Query(1,a,b));
}
else{
scanf("%d%d%d",&a,&b,&c);
Update(c,a,b,1);
}
}
}
return 0;
}