前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >洛谷P3372 【模板】线段树 1(树状数组)

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

作者头像
attack
发布2018-10-08 11:36:35
5360
发布2018-10-08 11:36:35
举报

题意

题目链接

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$

代码语言:javascript
复制
#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;
}
/*
*/
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-10-01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题意
  • Sol
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档