A Simple Problem with Integers
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 102779 | Accepted: 32092 | |
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
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define mst(a,b) memset((a),(b),sizeof(a))
#define f(i,a,b) for(int i=(a);i<(b);++i)
#define rush() int T;scanf("%d",&T);while(T--)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
typedef long long ll;
const int maxn= 100005;
const ll mod = 1e9+7;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
ll tree[maxn<<2];
ll flag[maxn<<2];
int num[maxn];
void pushup(int rt)
{
tree[rt]=tree[rt<<1]+tree[rt<<1|1];
}
void pushdown(int l,int r,int rt)
{
if(flag[rt])
{
int m=(l+r)>>1;
flag[rt<<1]+=flag[rt];
flag[rt<<1|1]+=flag[rt];
tree[rt<<1]+=(m-l+1)*flag[rt];
tree[rt<<1|1]+=(r-(m+1)+1)*flag[rt];
flag[rt]=0;
}
}
void build(int l,int r,int rt)
{
if(l==r)
{
tree[rt]=num[l];
return;
}
int m=(l+r)>>1;
build(lson);
build(rson);
pushup(rt);
return;
}
void update(int x,int y,int num,int l,int r,int rt)
{
if(x<=l&&r<=y)
{
tree[rt]+=num*(r-l+1);
flag[rt]+=num;
return;
}
pushdown(l,r,rt);
int m=(l+r)>>1;
if(x<=m)
{
update(x,y,num,lson);
}
if(m<y)
{
update(x,y,num,rson);
}
pushup(rt);
}
ll query(int x,int y,int l,int r,int rt)
{
if(x<=l&&r<=y)
{
return tree[rt];
}
pushdown(l,r,rt);
int m=(l+r)>>1;
ll ans=0;
if(x<=m)
{
ans+=query(x,y,lson);
}
if(m<y)
{
ans+=query(x,y,rson);
}
return ans;
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
mst(flag,0);
mst(tree,0);
for(int i=1;i<=n;i++)
{
scanf("%d",&num[i]);
}
build(1,n,1);
for(int i=0;i<m;i++)
{
char ch[2];
int x,y;
scanf("%s%d%d",ch,&x,&y);
if(ch[0]=='Q')
{
printf("%I64d\n",query(x,y,1,n,1));
}
else
{
int c;
scanf("%d",&c);
update(x,y,c,1,n,1);
}
}
}
return 0;
}