POJ 3468 A Simple Problem with Integers 树状数组

题意:给一串序列,有两种操作:在给定区间每个数加上x;求出给定区间和值
思路:区间修改,区间查询。在差分数组的基础上多维护一个数组,可用数学证明推出差分数组和值和原来的数组和值之间的关系,设差分数组为b[i],另一数组为d[i],则d[i]=b[i]*(i-1),求x之前元素和变为sum(x)=x * ∑b(1~x)-∑d(1 ~x)

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
#include<map>
#include<algorithm>
#define lowbit(x) (x&-x)
using namespace std;
typedef long long ll;
const int maxn = 1e5+5;
const int inf = 0x3f3f3f3f;
ll n, q, a[maxn], c[maxn], c2[maxn];
void add(ll x, ll t)
{
	for (ll i = x; i <= n; i += lowbit(i)) {
		c[i] += t;
		c2[i] += t*(x-1);
	}
}
ll sum(ll x)
{
	ll s = 0;
	for (ll i = x; i; i -= lowbit(i))
		s += x*c[i] - c2[i];
	return s;
}
int main()
{
	while (~scanf("%lld%lld", &n, &q)) {
		a[0] = 0;
		for (ll i = 1; i <= n; i++) {
			scanf("%lld", &a[i]);
			add(i, a[i]-a[i-1]);
		}
		char c;
		for (ll i = 1; i <= q; i++) {
			scanf(" %c", &c);
			if (c == 'Q') {
				ll x, y;
				scanf("%lld%lld", &x, &y);
				printf("%lld\n", sum(y)-sum(x-1));
			}
			else if (c == 'C') {
				ll x, y, t;
				scanf("%lld%lld%lld", &x, &y, &t);
				add(x, t);
				add(y+1, -t);
			}
		}
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值