poj 3468 A Simple Problem with Integers(线段树成段更新lazy)

37 篇文章 0 订阅
16 篇文章 0 订阅
本文介绍了一道POJ 3468题目,涉及如何使用线段树来处理区间内的整数操作,包括成段更新和求区间和。题目要求在10万规模的数据下处理两种操作:一种是将一个数值加到指定区间的所有数上,另一种是查询指定区间的数之和。输入包含初始整数数组和操作指令,输出是对所有指令的响应结果。
摘要由CSDN通过智能技术生成

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

solution:

LAZY模板题~

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 1e5+200;
#define ls t<<1
#define rs (t<<1)|1
struct node{
	long long val,lazy;
	int l, r;
}tree[maxn * 4];
void pushup(int t)
{
	tree[t].val = tree[ls].val + tree[rs].val;
}
void build(int l, int r, int t)
{
	tree[t].l = l;
	tree[t].r = r;
	tree[t].lazy = 0;
	if (l == r)
	{
		scanf("%lld", &tree[t].val);
		return;
	}
	build(l, (l + r) / 2, ls);
	build((l + r) / 2 + 1, r, rs);
	pushup(t);
}
void pushdown(int t)
{
	if (tree[t].lazy)
	{
		tree[ls].lazy+= tree[t].lazy;
		tree[ls].val+= (tree[ls].r - tree[ls].l + 1)*tree[t].lazy;
		tree[rs].lazy+= tree[t].lazy;
		tree[rs].val+= (tree[rs].r - tree[rs].l + 1)*tree[t].lazy;
		tree[t].lazy = 0;
	}
}

void update(int l,int r,int t,long long k)
{
	if (tree[t].l >= l&&tree[t].r <= r)
	{
		tree[t].lazy += k;
		tree[t].val+= (tree[t].r - tree[t].l + 1)*k;
		return;
	}
	pushdown(t);
	int mid = (tree[t].l + tree[t].r) / 2;
	if (l <= mid)update(l, r, ls, k);
	if (r > mid)update(l, r, rs, k);
	pushup(t);
}
long long Query(int l, int r, int t)
{
	long long sum = 0;
	if (tree[t].l >= l&&tree[t].r <= r)
		return tree[t].val;
	pushdown(t);
	int mid = (tree[t].l + tree[t].r) / 2;
	if (l <= mid)sum+=Query(l, r, ls);
	if (r > mid)sum+=Query(l, r, rs);
	return sum;
}
int main()
{
	int t, n, m, nn, x, y;
	long long z;
	char op[10];
	while (~scanf("%d%d", &n, &m))
	{
		build(1, n, 1);
		while (m--)
		{
			scanf("%s%d%d", op, &x, &y);
			if (op[0] == 'Q')printf("%lld\n", Query(x, y, 1));
			else {
				scanf("%lld", &z);
				update(x, y, 1, z);
			}
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值