1. 首页
  2. 线段树

Poj3468 A Simple Problem with Integers (成段更新)

题目链接:点我~~

线段树功能:update:成段增减 query:区间求和

不再是替换,而是增减,修改对应标记的增减~

//#include <bits/stdc++.h>
#include<cstdio>
#include<iostream>
using namespace std;

#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1

typedef long long LL;
const int MAXN = 100550;

LL sum[MAXN << 2];
LL col[MAXN << 2];

void pushup(int rt) {
	sum[rt] = sum[rt << 1] + sum[rt << 1 | 1];
}

void pushdown(int rt, int s) {
	if (col[rt]) {
		col[rt << 1] += col[rt];
		col[rt << 1 | 1] += col[rt];
		sum[rt << 1] += (s - (s >> 1)) * col[rt];
		sum[rt << 1 | 1] += (s >> 1) * col[rt];
		col[rt] = 0;
	}
}

void build(int l, int r, int rt) {
	col[rt] = 0;
	if (l == r) {
		scanf("%lld", &sum[rt]);
		return;
	}
	int m = (l + r) >> 1;
	build(lson);
	build(rson);
	pushup(rt);
}

void update(int L, int R, int ans, int l, int r, int rt) {
	if (L <= l && r <= R) {
		col[rt] += ans;
		sum[rt] += ans * (r - l + 1);
		return;
	}
	pushdown(rt, r - l + 1);
	int m = (l + r) >> 1;
	if (L <= m) {
		update(L, R, ans, lson);
	}
	if (R > m) {
		update(L, R, ans, rson);
	}
	pushup(rt);
}

LL query(int L, int R, int l, int r, int rt) {
	if (L <= l && r <= R) {
		return sum[rt];
	}
	pushdown(rt, r - l + 1);
	LL res = 0;
	int m = (l + r) >> 1;
	if (L <= m) {
		res += query(L, R, lson);
	}
	if (R > m) {
		res += query(L, R, rson);
	}
	return res;
}

int main() {
	int n, q;
	scanf("%d%d", &n, &q);
	build(1, n, 1);
	char tmp;
	int a, b, c;
	while (q--) {
		cin >> tmp;
		if (tmp == 'C') {
			scanf("%d%d%d", &a, &b, &c);
			update(a, b, c, 1, n, 1);
		} else {
			scanf("%d%d", &a, &b);
			printf("%lld\n", query(a, b, 1, n, 1));
		}
	}

	return 0;
}

 

评分 0, 满分 5 星
0
0
看完收藏一下,下次也能找得到
  • 版权声明:本文基于《知识共享署名-相同方式共享 3.0 中国大陆许可协议》发布,转载请遵循本协议
  • 文章链接:http://www.carlstedt.cn/archives/658 (转载时请注明本文出处及文章链接)
上一篇:
:下一篇

发表评论

gravatar

快来吐槽一下吧!

  1. .01 4:06
  2. .02 1:47
  3. .03 3:39
  4. .04 1:40