POJ-3468 A Simple Problem with Integers (树状数组)( 差分)

POJ-3468 A Simple Problem with Integers (树状数组)( 差分)

树状数组本来的特性是可进行单点修改的对前缀和的动态维护。如果涉及到区间修改的问题,就需要运用差分的思想,通过对差分数组前缀和的维护来达到对区间数据进行动态修改的效果。

设原始数据存入arr数组中,区间修改的操作由dif数组记录,则有:

请添加图片描述

故,可以用一个原始数据的前缀和数组和两个用树状数组维护的差分数组来实现区间修改区间查询的功能。

!请添加图片描述

代码:

#include <iostream>
#include <fstream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#pragma warning(disable:4996)
#define inr register int
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define debug(a) cout << #a << " " << a << endl
using namespace std;
typedef long long ll;
const int maxn = 100007;//1e5+7 
const ll mod = 1000000007;//1e9+7

int n;
int arr[maxn];
ll c1[maxn], c2[maxn], sum[maxn];

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

void update(ll* array, int p, ll x)
{
	while (p <= n) {
		array[p] += x;
		p += lowbit(p);
	}
}

ll getsum(ll* array, int p)
{
	ll res = 0;
	while (p > 0) {
		res += array[p];
		p -= lowbit(p);
	}
	return res;
}

int main()
{
	int m;
	ll ans = 0;
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= n; i++) {
		scanf("%d", arr + i);
	}
	for (int i = 1; i <= n; i++) {
		sum[i] = sum[i - 1] + arr[i];
	}
	char op;
	int opl, opr, opx;
	while (m--) {
		op = 0;
		while (op != 'C' && op != 'Q') { op = getchar(); }
		scanf("%d%d", &opl, &opr);
		if (op == 'C') {
			scanf("%d", &opx);
			update(c1, opl, opx);
			update(c1, opr + 1, -opx);
			update(c2, opl, opx * opl);
			update(c2, opr + 1, -opx * (opr + 1));
		}
		else {
			ans = sum[opr] - sum[opl - 1];
			ans += (opr + 1) * getsum(c1, opr) - getsum(c2, opr);
			ans -= (opl * getsum(c1, opl - 1) - getsum(c2, opl - 1));
			printf("%lld\n", ans);
		}
	}
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值