pku3468 A Simple Problem with Integers

典型的线段树区间更新、区间查询题目,代码基本上是自己根据理解写出来的
注:之前的版本写的不好,现在的是修改后的

#include <cstdio>
#include <cstring>
#include <algorithm>
using std::min;
using std::max;

typedef long long LL;
const int size = 100000 + 5;
int A, N, Q;
LL B[size];

struct tree_t {
	tree_t() : below(0), cover(0) { }
	LL below, cover;
} tree[size * 3];

int left, right;
LL delta;
void add(int low, int high, int node)
{
	if (left <= low && high <= right) {
		tree[node].cover += delta;
		tree[node].below += delta * (high - low + 1);
	} else if (left <= high && low <= right) {
		int mid = (low + high) / 2;
		add(low, mid, node * 2);
		add(mid + 1, high, node * 2 + 1);
		tree[node].below += delta * (min(high, right) - max(low, left) + 1);
	}
}

LL query(int low, int high, int node)
{
	if (left <= low && high <= right) {
		return tree[node].below;
	} else if (left <= high && low <= right) {
		int mid = (low + high) / 2;
		LL sum = 0;
		sum += query(low, mid, node * 2);
		sum += query(mid + 1, high, node * 2 + 1);
		sum += tree[node].cover * (min(high, right) - max(low, left) + 1);
		return sum;
	}
	return 0;
}

int main()
{
	scanf("%d%d", &N, &Q);
	B[0] = 0;
	for (int i = 1; i <= N; ++i)
	{
		scanf("%d", &A);
		B[i] = B[i - 1] + A;
	}
	
	char op;
	int a, b, c;
	while (Q--)
	{
		scanf(" %c", &op);
		if (op == 'C') {
			scanf("%d%d%d", &a, &b, &c);
			left = a, right = b, delta = c;
			add(1, N, 1);
		} else {
			scanf("%d%d", &a, &b);
			left = a, right = b;
			printf("%lld\n", query(1, N, 1) + B[b] - B[a - 1]);
		}
	}
	return 0;
}

你可能感兴趣的:(C++,c,C#)