A simple problem with integers
Time Limit: 5000MS |
|
Memory Limit: 131072K |
Total Submissions: 77486 |
|
Accepted: 23862 |
Case Time Limit: 2000MS |
Description
You have N integers, a1, a2, ..., an. You need to deal with both kinds of operations. One type of operation is to add some given number to each number in a given interval. The other are to ask for the sum of numbers in a given interval.
Input
The first line contains the 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
2 3 4 5 6 7 8 9 10Q 4 4Q 1 10Q 2 4C 3 6 3Q 2 4
Sample Output
455915
Hint
The sums may exceed the range of 32-bit integers.
Source
POJ monthly--2007.11.25, Yang Yi
Title Link: http://poj.org/problem?id=3468
The main topic: C When the number of a-B in the interval to add a c,q case when the value of the query interval.
Problem-Solving ideas: Template segment tree segments update problems.
The code is as follows:
#include <cstdio> #include <cstring> #define INF 1e12#define ll long const LL MAXN=1000010;LL n,m,a,b,c;ll Sum[maxn],nd[maxn];char s[2];void Build (ll l,ll R,ll root) {ll mid= (l+r)/2;if (l==r) {scanf ("%lld", &sum[root]); return;} Build (l,mid,root*2); build (mid+1,r,root*2+1); sum[root]=sum[root*2]+sum[root*2+1];} void Pushdown (ll l,ll root) {if (nd[root]!=0) {nd[root*2]+=nd[root];nd[root*2+1]+=nd[root];sum[root*2]+= ((L-L/2) *nd[ Root]); sum[root*2+1]+= ((L/2) *nd[root]); nd[root]=0;}} ll query (ll l,ll r,ll root) {if (l>=a&&r<=b) return sum[root];p ushdown (r-l+1,root); ll mid= (l+r)/2,ans=0; if (a<=mid) ans+=query (l,mid,root*2); if (B>mid) ans+=query (mid+1,r,root*2+1); return ans;} void Update (ll l,ll r,ll root) {if (l>b| | R<a) Return;ll len=r-l+1;if (l>=a&&r<=b) {nd[root]+=c;sum[root]+= (len*c); return;} Pushdown (len,root); int mid= (L+R)/2;if (a<=mid) Update (L,MID,ROOT*2), if (b>mid) update (mid+1,r,root*2+1); sum[ ROOT]=SUM[ROOT*2]+SUM[ROOT*2+1];} int main (void) {memset (ND,0,sizeof (ND)), scanf ("%lld%lld", &n,&m), Build (1,n,1), for (ll i=0;i<m;i++) {scanf ("%s", s), if (s[0]== ' Q ') { scanf ("%lld%lld", &a,&b);p rintf ("%lld\n", Query (1,n,1));} ELSE{SCANF ("%lld%lld%lld", &a,&b,&c); update (1,n,1);}}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
POJ 3468 A simple problem with integers (segment tree segments updated)