Time Limit: 5000MS | Memory Limit: 131072K | |
Total Submissions: 80166 | Accepted: 24744 | |
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
苟蒻上周才学的这题忘记写博客瞬间忘了什么鬼?!!!!
好吧。。其实线段树轻松AC但是学长执意要我学树状数组
树状数组不是只支持单点修改吗(hehehe)
设sum[i]表示前i项前缀和,c1[i]代表从i项开始到n的变化量,x为查询序列长度
于是ans = sum[r]-sum[l-1]+c1[l]*x+c1[l+1]*(x-1)+c1[l+2]*(x-2)+...+c1[r]*1
= sum[r]-sum[l-1]+segema(c1[i]*(r-i+1))
= sum[r]-sum[l-1]+(r+1)*segema(c1[i])-i*segema(c1[i])
那再设个c2[i]=i*c1[i]再加个树状数组就完成啦!
#include<cstdio> #include<iostream> #include<algorithm> #include<cstring> #include<string> #include<queue> #include<stack> #include<vector> #include<cstdlib> #include<map> #include<cmath> #include<set> using namespace std; const int maxn = 1e5 + 10; typedef long long LL; LL c1[maxn],c2[maxn],sum[maxn]; int i,j,n,m; LL Sum(int r) { LL ret = 0; int y; LL x = r; for (y = r; y > 0; y -= y&-y) ret += ((x+1)*c1[y] - c2[y]); return ret; } void Modify (int y,LL k) { LL d = y; for (; y <= n; y += y&-y) c1[y] += k,c2[y] += d*k; } int main() { #ifndef ONLINE_JUDGE #ifndef YZY freopen(".in","r",stdin); freopen(".out","w",stdout); #else freopen("yzy.txt","r",stdin); #endif #endif cin >> n >> m; for (i = 1; i <= n; i++) scanf("%lld",&sum[i]),sum[i] += sum[i-1]; while (m--) { int l,r; LL k; char c[2]; scanf("%s",c); if (c[0] == 'Q') { scanf("%d%d",&l,&r); LL ans = sum[r] - sum[l-1]; ans += Sum(r) - Sum(l-1); printf("%lld\n",ans); } else { scanf("%d%d%lld",&l,&r,&k); Modify(l,k); Modify(r+1,-k); } } return 0; }