[代码] codevs 1082 线段树练习3(树状数组)

- 传送门 -

 http://codevs.cn/problem/1082/
 

1082 线段树练习 3

时间限制: 3 s

空间限制: 128000 KB

题目等级 : 大师 Master

题目描述 Description

给你N个数,有两种操作:

1:给区间[a,b]的所有数增加X

2:询问区间[a,b]的数的和。

输入描述 Input Description

第一行一个正整数n,接下来n行n个整数,

再接下来一个正整数Q,每行表示操作的个数,

如果第一个数是1,后接3个正整数,

表示在区间[a,b]内每个数增加X,如果是2,

表示操作2询问区间[a,b]的和是多少。

pascal选手请不要使用readln读入

输出描述 Output Description

对于每个询问输出一行一个答案

样例输入 Sample Input

3
1
2
3
2
1 2 3 2
2 2 3

样例输出 Sample Output

9

数据范围及提示 Data Size & Hint

1<=n<=200000

1<=q<=200000
 

- 代码 -

#include<cstdio>
using namespace std;

typedef long long ll;
const int M = 2e5 + 5;

ll A[M], B[M], C[M];
int n, m, x, y, p, v;
int f;
char ch;

template <typename T> void read(T &x) {
	x = 0; f = 1; ch = getchar();
	while (ch > '9' || ch < '0') { if (ch == '-') f = -1; ch = getchar(); }
	while (ch >= '0' && ch <= '9') { x = x*10 + ch - '0'; ch = getchar(); }
	x *= f;
}

int lowbit(int x) { return x&(-x); }

void upt(int x, ll v) {
	int k = x;
	while (x <= n) {
		B[x] += v;
		C[x] += 1ll * v * k;
		x += lowbit(x);
	}
}

ll ask(int x) {
	ll ans = 0;
	int k = x;
	while (x > 0) {
		ans += (k + 1) * B[x] - C[x];
		x -= lowbit(x);
	}
	return ans;
}

int main() {
	read(n);
	for (int i = 1; i <= n; ++ i) {
		read(A[i]);
		upt(i, A[i] - A[i-1]);
	}
	read(m);
	for (int i = 1; i <= m; ++i) {
		read(p); read(x); read(y);
		if (p == 1) {
			read(v);
			upt(x, v); upt(y + 1, -v);
		}
		else printf("%lld
", ask(y) - ask(x - 1));
	}
	return 0;
}
原文地址:https://www.cnblogs.com/Anding-16/p/7300708.html