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;
}