[树状数组] C - A Simple Problem with Integers POJ - 3468

A Simple Problem with Integers
Time Limit: 5000MS   Memory Limit: 131072K
Total Submissions: 133197   Accepted: 41317
Case Time Limit: 2000MS

Description

You have N integers, A1A2, ... , 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 A1A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of AaAa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of AaAa+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




/// 树状数组 区间更新 区间求和
#include <iostream>
#include <cstdio>
using namespace std;

const int mn = 1e5 + 10;
const int mq = 1e5 + 10;

int n, q;
long long a[mn], b0[mn], b1[mn];

void add(long long b[], int i, int v)
{
	while (i <= n)
	{
		b[i] += v;
		i += i & (-i);
	}
	return;
}

long long sum(long long b[], int i)
{
	long long res = 0;
	while (i > 0)
	{
		res += b[i];
		i -= i & (-i);
	}
	return res;
}

int main()
{
	scanf("%d %d", &n, &q);
	for (int i = 1; i <= n; i++)
	{
		scanf("%lld", &a[i]);
		add(b0, i, a[i]);  // b0 初始化 为对应范围a[]的和
	}
	
	while (q--)
	{
		char ch[2];
		scanf("%s", ch);
		int l, r;
		scanf("%d %d", &l, &r);
		if (ch[0] == 'C')
		{
			long long x;
			scanf("%lld", &x);
			add(b0, l, -x * (l - 1));
			add(b0, r + 1, x * r);
			add(b1, l, x);
			add(b1, r + 1, -x);
		}
		
		else if (ch[0] == 'Q')
		{	/// sum[i] = sumb0[i] + sumb1[i] * i
			long long sumr = sum(b0, r) + sum(b1, r) * r;
			long long suml = sum(b0, l - 1) + sum(b1, l - 1) * (l - 1);
			printf("%lld\n", sumr - suml);
		}
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ummmmm/article/details/80986894
今日推荐