POJ A Simple Problem with Integers
http://poj.org/problem?id=3468
A Simple Problem with Integers
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 34676 | Accepted: 9917 | |
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
View Code
#include<stdio.h> typedef __int64 LL; struct SegmentTree{ int left,right; LL sum,add; }f[600000]; LL value[100100]; LL build(int left,int right,int k){ f[k].left=left, f[k].right=right; f[k].add = 0; if(left==right){ return f[k].sum = value[left]; } int mid= (left+right)>>1; return f[k].sum=build(left,mid,k<<1)+build(mid+1,right,k<<1|1); } void update(int left,int right,LL add,int k){ if(left==f[k].left&&right==f[k].right){ f[k].add+=add; f[k].sum+=(f[k].right-f[k].left+1)*add; return ; } if(f[k].add){ f[k<<1].add+=f[k].add; f[k<<1|1].add+=f[k].add; f[k<<1].sum+=(f[k<<1].right-f[k<<1].left+1)*f[k].add; f[k<<1|1].sum+=(f[k<<1|1].right-f[k<<1|1].left+1)*f[k].add; f[k].add=0; } int mid = (f[k].left+f[k].right)>>1; if(right<=mid) update(left,right,add,k<<1); else if(left>mid) update(left,right,add,k<<1|1); else{ update(left,mid,add,k<<1); update(mid+1,right,add,k<<1|1); } f[k].sum=f[k<<1].sum+f[k<<1|1].sum; } LL query(int left,int right,int k){ if(f[k].left==left&&f[k].right==right) return f[k].sum; if(f[k].add){ f[k<<1].add+=f[k].add; f[k<<1|1].add+=f[k].add; f[k<<1].sum+=(f[k<<1].right-f[k<<1].left+1)*f[k].add; f[k<<1|1].sum+=(f[k<<1|1].right-f[k<<1|1].left+1)*f[k].add; f[k].add=0; } int mid = (f[k].left+f[k].right)>>1; if(right<=mid) return query(left,right,k<<1); else if(left>mid) return query(left,right,k<<1|1); else return query(left,mid,k<<1)+query(mid+1,right,k<<1|1); } int main(){ int n,q; scanf("%d%d",&n,&q); for(int i=1;i<=n;i++) scanf("%I64d",&value[i]); build(1,n,1); while(q--){ char s[2]; scanf("%s",s); if(s[0]=='Q'){ int left,right; scanf("%d%d",&left,&right); printf("%I64d\n",query(left,right,1)); } else{ int left,right; LL add; scanf("%d%d%I64d",&left,&right,&add); update(left,right,add,1); } } return 0; }