A Simple Problem with Integers
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 137519 | Accepted: 42602 | |
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
线段树板子题,区间[a,b]内的每个数都加ans;
#include <iostream>//区间更新;注意和为long long
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
#define maxn 100010
ll n,q;
ll tree[maxn<<2], vis[maxn<<2]={0};//用vis数组做延迟标记
void build(ll l,ll r,ll rt){
if(l == r){
scanf("%lld",&tree[rt]);
return;
}
ll mid=(l+r)>>1;
build(l,mid,rt<<1);
build(mid+1,r,rt<<1|1);
tree[rt] = tree[rt<<1]+tree[rt<<1|1];
}
void solve(ll l,ll r,ll rt){//用来处理vis数组
if(vis[rt] == 0) return;//没有标记证明这个区间没有要加的数
ll mid=(l+r)>>1;
tree[rt<<1] += vis[rt]*(mid+1-l);//左孩子
tree[rt<<1|1] += vis[rt]*(r-mid);//右孩子
vis[rt<<1] += vis[rt];//标记往下一层,左右孩子都要加;
vis[rt<<1|1] += vis[rt];
vis[rt] = 0;//注意清零
}
void update(ll a,ll b,ll ans,ll l,ll r,ll rt){//区间[a,b]内的每个数都加ans
if(a <= l && b >= r){
tree[rt] += ans*(r+1-l);//区间有几个数就加几个ans
vis[rt] += ans;//vis数组标记,每个子节点都加上ans
return;
}
solve(l,r,rt);
ll mid=(l+r)>>1;
if(a <= mid) update(a,b,ans,l,mid,rt<<1);
if(b > mid) update(a,b,ans,mid+1,r,rt<<1|1);
tree[rt] = tree[rt<<1]+tree[rt<<1|1];
}
ll ask(ll a,ll b,ll l,ll r,ll rt){
if(a <= l && b >= r){
return tree[rt];
}
solve(l,r,rt);//注意查询的时候也要处理一下vis数组
ll mid=(l+r)>>1;
ll ans = 0;
if(a <= mid) ans += ask(a,b,l,mid,rt<<1);
if(b > mid) ans += ask(a,b,mid+1,r,rt<<1|1);
return ans;
}
int main(){
scanf("%d%d",&n,&q);
build(1,n,1);
char c;
ll a,b,x;
while(q--){
cin>>c;
if(c == 'Q') {
scanf("%lld%lld",&a,&b);
printf("%lld\n",ask(a,b,1,n,1));
}
else {
scanf("%lld %lld %lld",&a,&b,&x);
update(a,b,x,1,n,1);
}
}
return 0;
}