题目链接:http://poj.org/problem?id=3468
Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 144616 | Accepted: 44933 | |
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
Source
//参考《算法竞赛进阶指南》 #include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<string> #include<queue> #include<vector> #include<set> #include<map> using namespace std; typedef long long ll; const int maxn=100010; ll a[maxn],sum[maxn],add[maxn]; int L[maxn],R[maxn]; int pos[maxn]; int n,m,t; void change(int l,int r,ll d) { int p = pos[l],q = pos[r]; if(p == q) { for(int i=l;i<=r;i++) a[i] += d; sum[p] += (r-l+1)*d; } else { for(int i=p+1;i<=q-1;i++) add[i] += d; for(int i=l;i<=R[p];i++) a[i] += d; sum[p] += (R[p]-l+1)*d; for(int i=L[q];i<=r;i++) a[i] += d; sum[q] += (r-L[q]+1)*d; } } ll ask(int l,int r) { int p = pos[l],q = pos[r]; ll ans = 0; if(p == q) { for(int i=l;i<=r;i++) ans += a[i]; ans += add[p]*(r-l+1); } else { for(int i=p+1;i<=q-1;i++) ans += (sum[i]+add[i]*(R[i]-L[i]+1)); for(int i=l;i<=R[p];i++) ans += a[i]; ans += add[p]*(R[p]-l+1); for(int i=L[q];i<=r;i++) ans +=a[i]; ans += add[q]*(r-L[q]+1); } return ans; } int main() { int i,j; char c; while(cin>>n>>m) { memset(sum,0,sizeof(sum)); memset(add,0,sizeof(add)); for(i=1;i<=n;i++) scanf("%lld",&a[i]); //分块 t = sqrt(n); for(i=1;i<=t;i++) { L[i] = (i-1)*sqrt(n) + 1; R[i] = i*sqrt(n); } if(R[t] < n) t++,L[t] = R[t-1] + 1,R[t] = n; //预处理 for(i=1;i<=t;i++) for(j=L[i];j<=R[i];j++) { pos[j] = i; sum[i] += a[j]; } while(m--) { getchar(); scanf("%c",&c); if(c == 'Q') { int x,y; scanf("%d%d",&x,&y); cout<<ask(x,y)<<endl; } else { int l,r; ll val; scanf("%d%d%lld",&l,&r,&val); change(l,r,val); } } } return 0; }