码迷,mamicode.com
首页 > 编程语言 > 详细

P3368【模板】树状数组 2 - 差分

时间:2018-10-14 11:44:03      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:scanf   date   update   max   algorithm   cer   deb   define   pac   

建立两个差分数组,套公式就好了
c[i]表示i元素的“增量”,下面的式子左边是序列从1 ~ x的前缀和整体增加的值
\[\sum_{i=1}^x\sum_{j=1}^ic[j] = (x+1)\sum_{i=1}^xc[i] - \sum_{i=1}^xi*c[i] \]

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
#define debug(x) cerr << #x << "=" << x << endl;
const int MAXN = 500000 + 10;
int n,m,tr[MAXN],c1[MAXN],c2[MAXN],sum[MAXN];
void update(int k, int p, int c[]) {
    while(p <= n) {
        c[p] += k;
        p += p&(-p);
    }
}
int getsum(int p, int c[]) {
    int sum = 0;
    while(p) {
        sum += c[p];
        p -= p&(-p);
    }
    return sum;
}
int main() {
    scanf("%d%d", &n, &m);
    for(int i=1; i<=n; i++) {
        int ai = 0;
        scanf("%d", &ai);
        sum[i] = sum[i-1] + ai;
    }
    for(int i=1; i<=m; i++) {
        int cmd, x, y, k;
        scanf("%d", &cmd);
        if(cmd == 1) {
            scanf("%d%d%d", &x, &y, &k);
            update(k, x, c1), update(-k, y+1, c1);
            update(k*x, x, c2), update(-k * (y+1), y+1, c2);
        } else {
            scanf("%d", &x);
            int ls = sum[x-1] + x * getsum(x-1, c1) - getsum(x-1, c2);
            int rs = sum[x] + (x+1) * getsum(x, c1) - getsum(x, c2);
            printf("%d\n", rs - ls);
        }
    }
    return 0;
} 

P3368【模板】树状数组 2 - 差分

标签:scanf   date   update   max   algorithm   cer   deb   define   pac   

原文地址:https://www.cnblogs.com/Zolrk/p/9785343.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!