AcWing243. A simple integer problem 2 ( interval modification of tree array + interval query )
a 1 + a 2 + a 3 + a … a x a_{1}+a_{2}+a_{3}+a\dots a_{x} a1+a2+a3+a…ax = = == == ∑ i = 1 x ∑ j = 1 i b j \sum^{x}_{i = 1}\sum^{i}_{j = 1}b_{j} ∑i=1x∑j=1ibj
Given a sequence A of length N and M instructions, each instruction may be one of the following two:
1. "C lrd" means adding d to all A[l], A[l+1],...,A[r].
2. "Q lr" means the sum of the number l~r in the query sequence.
For each query, output an integer to indicate the answer.
Input format
Two integers N and M in the first line.
N integers A[i] in the second line.
The next M lines represent M instructions, and the format of each instruction is shown in the title description.
Output format
For each query, output an integer to indicate the answer.
Each answer is on a line.
data range
1 ≤ N , M ≤ 1 0 5 , 1≤N,M≤10^{5}, 1≤N,M≤105,
∣ d ∣ ≤ 10000 |d|≤10000 ∣d∣≤10000
∣ A [ i ] ∣ ≤ 1000000000 |A[i]|≤1000000000 ∣A[i]∣≤1000000000
Code
#include <iostream>
using namespace std;
typedef long long LL;
const int N = 100010;
int n , m;
int a[N];
LL tr1[N] , tr2[N];
int lowbit(int x)
{
return x & -x;
}
void add(LL tr[] , int x , LL c)
{
for(int i = x ; i <= n ; i += lowbit(i)) tr[i] += c;
}
LL sum(LL tr[] , int x)
{
LL res = 0;
for(int i = x ; i ; i -= lowbit(i)) res += tr[i];
return res;
}
LL prefix_sum(int x)
{
return sum(tr1 , x) * (x + 1) - sum(tr2 , x);
}
int main()
{
scanf("%d%d" , &n , &m);
for(int i = 1; i <= n ; i++) scanf("%d", &a[i]);
for(int i = 1 ; i <= n ; i++)
{
int b = a[i] - a[i - 1];
add(tr1 , i , b);
add(tr2 , i , (LL)b * i);
}
while(m--)
{
int l , r , d;
char op[2];
scanf("%s%d%d" , op , &l , &r);
if(*op == 'Q')
cout << prefix_sum(r) - prefix_sum(l - 1) << endl;
else
{
scanf("%d" , &d);
add(tr1 , l , d) , add(tr1 , r + 1 , -d);
add(tr2 , l , l * d) , add(tr2 , r + 1 , (r + 1) * (- d));
}
}
return 0;
}