POJ3468 A Simple Problem with Integers 分块

题目链接

http://poj.org/problem?id=3468

分析

将原序列划分成若干段长度为 ⌊ n ⌋ \lfloor \sqrt{n} \rfloor n 的区间进行维护;

a [ i ] a[i] a[i] 以表示原序列每个元素, b [ i ] b[i] b[i] 表示每个元素所属的区间,

s u m [ i ] sum[i] sum[i] 表示每个区间的元素之和, a d d [ i ] add[i] add[i] 表示每个区间的增量。

AC代码

#include 
#include 

inline int read() {
	int num = 0, flag = 1;
	char c = getchar();
	while (c < '0' || c > '9') {
		if (c == '-') flag = -1;
		c = getchar();
	}
	while (c >= '0' && c <= '9')
		num = num * 10 + c - '0', c = getchar();
	return flag * num;
}

const int maxn = 1e5 + 5, maxs = 320;

int a[maxn], b[maxn], len[maxs], add[maxs];
long long sum[maxs];

inline void modify(int l, int r, int d) {
	if (b[l] == b[r])
		for (int i = l; i <= r; ++i) a[i] += d, sum[b[i]] += d;
	else {
		for (int i = l; b[i] == b[l]; ++i) a[i] += d, sum[b[i]] += d;
		for (int i = r; b[i] == b[r]; --i) a[i] += d, sum[b[i]] += d;
		for (int i = b[l] + 1; i <= b[r] - 1; ++i) add[i] += d;
	}
}

inline long long query(int l, int r) {
	long long ret = 0;
	if (b[l] == b[r]) {
		for (int i = l; i <= r; ++i) ret += a[i] + add[b[i]];
		return ret;
	}
	for (int i = l; b[i] == b[l]; ++i) ret += a[i] + add[b[i]];
	for (int i = r; b[i] == b[r]; --i) ret += a[i] + add[b[i]];
	for (int i = b[l] + 1; i <= b[r] - 1; ++i)
		ret += sum[i] + 1ll * add[i] * len[i];
	return ret;
}

int main() {
	int n = read(), q = read();
	int s = sqrt(n);
	for (int i = 1; i <= n; ++i) {
		a[i] = read(), b[i] = b[i - 1] + (i % s == 1 ? 1 : 0);
		++len[b[i]], sum[b[i]] += a[i];
	}
	while (q--) {
		char op[2];
		scanf("%s", op);
		if (op[0] == 'C') {
			int x = read(), y = read(), z = read();
			modify(x, y, z);
		}
		else if (op[0] == 'Q') {
			int x = read(), y = read();
			printf("%lld\n", query(x, y));
		}
	}
	return 0;
}

你可能感兴趣的:(数据结构,《算法竞赛进阶指南》,题解)