poj 3468
A Simple Problem with Integers
Time Limit: 5000MS |
|
Memory Limit: 131072K |
Total Submissions: 90736 |
|
Accepted: 28268 |
Case Time Limit: 2000MS |
Description
You have N integers, A1, A2, ... , AN. You need to dealwith two kinds of operations. One type of operation is to add some given numberto each number in a given interval. The other is to ask for the sum of numbersin a given interval.
Input
The first linecontains 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 queryingthe sum of Aa, Aa+1, ... , Ab.
Output
You need to answerall Q commands in order. One answer in a line.
SampleInput
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
SampleOutput
4
55
9
15
Hint
The sumsmay exceed(超过) the range of 32-bit integers(整数).
Source
POJMonthly--2007.11.25, Yang Yi
注意:数组要用long long
线段树解法
Problem: 3468
User: ksq2013
Memory: 4776K
Time: 2532MS
Language: G++
Result: Accepted
#include<cstdio> #include<cstdlib> #include<iostream> using namespace std; int n,q; long long col[400001],sum[400001]; void pushup(int k) {sum[k]=sum[k<<1]+sum[k<<1|1];} void pushdown(int k,int m) { if(col[k]){ col[k<<1]+=col[k]; col[k<<1|1]+=col[k]; sum[k<<1]+=col[k]*(m-(m>>1)); sum[k<<1|1]+=col[k]*(m>>1); col[k]=0; } } void build(int s,int t,int k) { if(!(s^t)){ scanf("%lld",&sum[k]); return; }int m=(s+t)>>1; build(s,m,k<<1); build(m+1,t,k<<1|1); pushup(k); } void update(int s,int t,int k,int l,int r,int c) { if(l<=s&&t<=r){ col[k]+=c; sum[k]+=c*(t-s+1); return; }pushdown(k,t-s+1); int m=(s+t)>>1; if(l<=m)update(s,m,k<<1,l,r,c); if(m<r)update(m+1,t,k<<1|1,l,r,c); pushup(k); } long long query(int s,int t,int k,int l,int r) { if(l<=s&&t<=r)return sum[k]; pushdown(k,t-s+1); int m=(s+t)>>1; long long res=0; if(l<=m)res+=query(s,m,k<<1,l,r); if(m<r)res+=query(m+1,t,k<<1|1,l,r); return res; } int main() { scanf("%d%d",&n,&q); build(1,n,1); for(int i=1;i<=q;i++){ char ak[3]; scanf("%s",ak); if(ak[0]=='C'){ int a,b,c; scanf("%d%d%d",&a,&b,&c); update(1,n,1,a,b,c); } else{ int a,b; scanf("%d%d",&a,&b); printf("%lld\n",query(1,n,1,a,b)); } } return 0; }