POJ - 3648 A Simple Problem with Integers (树状数组)


A Simple Problem with Integers
Time Limit: 5000MS Memory Limit: 131072K
Total Submissions: 152104 Accepted: 47157
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

The sums may exceed the range of 32-bit integers.
Source

POJ Monthly--2007.11.25, Yang Yi

一组数组,两种操作
查询\([i,j]\)区间的和,或者把\([i,j]\)区间上的值都加上一个数

树状数组 区间修改 区间查询
一开始是一个点一个点修改,然后TLE了,后来网上看了一下别人是怎么维护的
贴上连接https://www.cnblogs.com/lcf-2000/p/5866170.html
然后复述一下
\(a{_i}\)表示第i个数据,建立一个数组d,\(d{_i} = a{_i} - a{_{i-1}}\) ,这里假设\(a{_0} = 0\),

\[a{_x} = \sum_{i = 1}^xdi \]

\[\sum_{i = 1}^xa_x = \sum_{i=1}^x\sum_{j=1}^idj = \sum_{i=1}^x(x - i + 1)di=\sum_{i=1}^x(x+1)d_i-\sum_{i=1}^x d_i*i \]

这样每次更改区间的时候只要更新两个两个点就可以了

#include
#include
#define ll long long

ll a[100001] = {},b[100001] = {},c[100001] = {},d[100001] = {};
int n,q;
	
int lowbit(ll x)
{
	return x & -x;
}

ll sum(ll x)
{
	ll num = 0,mul = x;
	while (x > 0)
	{
		num += (mul + 1) * c[x] - d[x];
		x = x - lowbit(x);
	}
	return num;
}
void change(ll x,ll w)
{
	ll u = x;
	while (u <= n)
	{
		c[u] += w;
		d[u] += w * x;
		u += lowbit(u);
	}
}

int main()
{
	scanf("%d%d",&n,&q);
	ll m,last = 0;
	for (ll i = 1;i<=n;i++)
	{
		scanf("%lld",&m);
		a[i] = a[i-1] + m - last;//计算di的前缀和 
		b[i] = b[i-1] + (m - last) * i;//计算di*i的前缀和 
		c[i] = a[i] - a[i - lowbit(i)];//树状数组存储di 
		d[i] = b[i] - b[i - lowbit(i)];//树状数组存储di*i 
		last = m;
	}
	for (int i = 1;i<=q;i++)
	{
		char check;
		ll u,v,w;
		getchar();
		check = getchar();
		if (check == 'Q')
		{
			scanf("%lld%lld",&u,&v);
			ll t = sum(v) - sum(u - 1);//区间查询 
			printf("%lld\n",t);
		}
		else
		{
			scanf("%lld%lld%lld",&u,&v,&w);
			change(u,w);//更改起点和前一个点的差值 
			change(v+1,-w);//更改后一个点和终点的差值 
		}
	}
}

蒟蒻的线段树学习orz