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.
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
const int M=100010;
long long add_sum[M];
long long add[M];
long long ori[M];
int MN;
int Q;
int lowbit(int x)
{return x&(-x);
}
void update(int i,int v,long long* a)
{for(;i<=MN;i+=lowbit(i)){a[i]+=v;}
}
long long getsum(int r,long long *a)
{long long resr=0;for(;r>0;r-=lowbit(r)){resr+=a[r];}return resr;
}
int main()
{//freopen("data.in","r",stdin);std::ios::sync_with_stdio(false);std::cin.tie(0);int tem;int l,r,val;while(cin>>MN>>Q){memset(ori,0,sizeof(ori));memset(add_sum,0,sizeof(add_sum));memset(add,0,sizeof(add));for(int i=1;i<=MN;i++){cin>>tem;update(i,tem,ori);}string ch;for(int i=0;i<Q;i++){cin>>ch;if(ch=="Q"){cin>>l>>r;cout<<getsum(r,ori)-getsum(l-1,ori)-l*getsum(l-1,add)+(r+1)*getsum(r,add)-getsum(r,add_sum)+getsum(l-1,add_sum)<<endl;}if(ch=="C"){cin>>l>>r>>val;update(l,val,add);update(r+1,-val,add);update(l,val*(l),add_sum);update(r+1,-val*(r+1),add_sum);}}}
}
#include<iostream>
#include<string.h>
#include<string>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
const int M = 4*100010;
long long sumv[M];//線段樹sum數組
long long add[M];
long long x, y;//全局變量,update與query時使用
long long addval;
long long _sum;
//*********************//
void update(int id, int l, int r)
{long long m = l + (r - l) / 2;if (x <= l&&y >= r){add[id] += addval;}else{if (x <= m) update(2 * id, l, m);if (y>m) update(2 * id + 1, m+1, r);}sumv[id]=0;//!!!!!!!!!注意此步驟if (l<r){sumv[id] = sumv[2 * id] + sumv[2 * id + 1];}sumv[id] += add[id] * (r - l + 1);
}
void query(int id, int l, int r, long long addv)
{long long m = l + (r - l) / 2;if (x <= l&&y >= r){_sum += sumv[id] + addv*(r - l + 1);}else{//addv += add[id];if (x <= m){query(2 * id, l, m, addv+add[id]);}if (y>m) query(2 * id + 1, m+1, r, addv+add[id]);}
}
int main()
{//freopen("data.in", "r", stdin);//freopen("data.out","w",stdout);std::ios::sync_with_stdio(false);std::cin.tie(0);long long n, q;while (cin >> n >> q){memset(sumv, 0, sizeof(sumv));memset(add, 0, sizeof(add));for (int i = 1; i <= n; i++){cin >> addval;x = i;y = i;update(1, 1, n);}string ch;for (int i = 0; i<q; i++){cin >> ch;if (ch == "Q"){_sum = 0;cin >> x >> y;query(1, 1, n, 0);cout << _sum << endl;}if (ch == "C"){cin >> x >> y >> addval;update(1, 1, n);}}}
}