poj 3468 A Simple Problem with Integers 【区间修改+区间查询(树状数组)】

题目连接:http://poj.org/problem?id=3468

参考下面博客的公式:(公式关键是 a[i] =  \sum_{j = 1}^{i} d[j]  d[j] 是差分数组,只要修改d[L] 和 d[R+1] 的值就能通过求d数组的前缀和得到单个a[] 的值,只要把 a数组的前缀和通过包含 d数组的表达式表达出来,就能只修改d数组的两个值得到a的前缀和)

https://www.cnblogs.com/lcf-2000/p/5866170.html

需要注意的是,输入初始数列的时候要 add 两次, L = R, add (L, x), add (R+1, -x)

#include 
#include 
#include 

using namespace std;

typedef long long ll;
const int Maxn = 1e5+10;

ll d[Maxn],di[Maxn];
int n;

void add (int x, int y) {
    int tmp = x;
    while (x <= n) {
        d[x] += y;
        di[x] += (ll)tmp*y;
        x += x&(-x);
    }
}

ll sum (int x) {  
    ll ret = 0, ans2 = 0; int tmp = x;
    while (x > 0) {
        ret+= (tmp+1)*d[x]-di[x];
        x -= x&(-x);
    }
    return ret;
}

int main (void)
{
    int m, tmp;
    scanf ("%d%d", &n, &m);
    for (int i = 1; i <= n; ++i) {
        scanf ("%d", &tmp);
        add (i, tmp);  // 注意输入初始值的时候需要 add两次, 
        add (i+1, -tmp); // L = R = i,add (L, x),add (R+1, -x)
    }
    char op[2]; int L, R, val;
    while (m--) {
        scanf ("%s", op);
        if (!strcmp (op, "C")) {
            scanf ("%d%d%d", &L, &R, &val);
            add (L, val);
            add (R+1, -val);
        } else {
            scanf ("%d%d", &L, &R);
            printf ("%lld\n", sum (R)-sum(L-1));
        }
    }
    return 0;
}

 

你可能感兴趣的:(树状数组)