poj 3468 A Simple Problem with Integers
A Simple Problem with Integers
Time Limit:5000MS Memory Limit:131072KB 64bit IO Format:%I64d & %I64u
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 abc" means adding c to each of Aa, Aa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q ab" 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.
#include<iostream> #include<cstdio> #include<cstring> using namespace std; #define maxn 200005 #define inf 0x3f3f3f3f typedef long long lls; lls a[maxn]; lls sum[maxn<<2],add[maxn<<2],ll[maxn<<2],rr[maxn<<2]; inline void pushup(int i){ sum[i]=sum[i<<1]+sum[i<<1|1]; } inline void pushdown(lls i,lls m){ if(add[i]){ sum[i<<1]+=add[i]*(m-(m>>1)); sum[i<<1|1]+=add[i]*(m>>1); add[i<<1]+=add[i]; add[i<<1|1]+=add[i]; add[i]=0; } } void build(lls l,lls r,lls i){ ll[i]=l; rr[i]=r; add[i]=0; if(l==r){ sum[i]=a[l]; return; } lls m=(ll[i]+rr[i])>>1,ls=i<<1,rs=ls|1; build(l,m,ls); build(m+1,r,rs); pushup(i); } void update(lls l,lls r,lls v,lls i){ if(ll[i]>=l&&rr[i]<=r){ add[i]+=v; sum[i]+=(lls)(rr[i]-ll[i]+1)*v; return ; } pushdown(i,rr[i]-ll[i]+1); lls m=(ll[i]+rr[i])>>1,ls=i<<1,rs=ls|1; if(l<=m)update(l,r,v,ls); if(m<r)update(l,r,v,rs); pushup(i); } lls query(lls l,lls r,lls i){ if(ll[i]>=l&&rr[i]<=r){ return sum[i]; } pushdown(i,rr[i]-ll[i]+1); lls m=(ll[i]+rr[i])>>1,ls=i<<1,rs=ls|1; lls ans=0; if(l<=m)ans+=query(l,r,ls); if(m<r)ans+=query(l,r,rs); return ans; } int main() { int n,qq; int u,v,c; //freopen("in.txt","r",stdin); while(~scanf("%d%d",&n,&qq)){ for(int i=1;i<=n;i++){ scanf("%lld",&a[i]); } build(1,n,1); char q[2]; while(qq--){ scanf("%s",&q); if(q[0]=='Q'){ scanf("%d%d",&u,&v); printf("%lld\n",query(u,v,1)); } else { scanf("%d%d%d",&u,&v,&c); update(u,v,c,1); } } } }