首页 > 编程语言 > 详细

洛谷P3372 【模板】线段树 1(树状数组)

时间:2018-10-01 18:40:09      阅读:193      评论:0      收藏:0      [点我收藏+]

题意

题目链接

Sol

Get到了这题树状数组的做法,感觉非常nice

区间加:直接差分

区间求和:考虑每一位的贡献

$sum_{i = 1}^x (x+1 - i) d_i$

$= sum_{i = 1}^x (x+1)d_i - \sum_{i = 1}^x id_i$

$= (x+1) sum_{i = 1}^x d_i - \sum_{i = 1}^x id_i$

#include<bits/stdc++.h>
#define lb(x) (x & (-x))
#define LL long long 
#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1<<22, stdin), p1 == p2) ? EOF : *p1++)
char buf[(1 << 22)], *p1 = buf, *p2 = buf;
char obuf[1<<24], *O = obuf;
void print(LL x) {if(x > 9) print(x / 10); *O++ = x % 10 + '0';}
#define OS  *O++ = '\n';
#define fout fwrite(obuf, O-obuf, 1 , stdout);
using namespace std;
const int MAXN = 1e5 + 10;
inline LL read() {
    char c = getchar(); LL x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-')f =- 1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int N, M;
LL a[MAXN], T1[MAXN], T2[MAXN];
void insert(LL *T, int pos, LL val) {
    while(pos <= N) T[pos] += val, pos += lb(pos);
}
LL sum(LL *T, int pos) {
    LL ans = 0;
    while(pos) ans += T[pos], pos -= lb(pos);
    return ans;
}
LL Query(int pos) {
    return 1ll * (pos + 1) * sum(T1, pos) - sum(T2, pos);
}
main() {
    N = read(); M = read();
    for(int i = 1; i <= N; i++) a[i] = read(), insert(T1, i, a[i] - a[i - 1]), insert(T2, i, 1ll * i * (a[i] - a[i - 1]));
    while(M--) {
        int opt = read(), l = read(), r = read();
        if(opt == 1) {
            LL val = read();
            insert(T1, l, val); insert(T1, r + 1, -val);
            insert(T2, l, 1ll * l * val); insert(T2, r + 1, 1ll * -(r + 1) * val);
        } else print(Query(r) - Query(l - 1)), OS;
    }
    fout;
}
/*
*/

洛谷P3372 【模板】线段树 1(树状数组)

原文:https://www.cnblogs.com/zwfymqz/p/9735306.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!