树状数组和线段树C++模板

题目:动态求连续区间和

树状数组

cpp 复制代码
#include <cstdio>
#define LL long long

const LL N = 100010;
LL n, m, a[N], tr[N];

LL lowbit(LL x)
{
    return x & -x;
}

void add(LL x, LL y)
{
    for (LL i = x; i <= n; i += lowbit(i))
        tr[i] += y;
}

LL query(LL x)
{
    LL res = 0;
    for (LL i = x; i >= 1; i -= lowbit(i))
        res += tr[i];
    return res;
}

int main()
{
    scanf("%lld%lld", &n, &m);
    for (LL i = 1; i <= n; i ++ )
    {
        scanf("%lld", &a[i]);
        add(i, a[i]);
    }
    
    while (m -- )
    {
        LL k, a, b;
        scanf("%lld%lld%lld", &k, &a, &b);
        if (!k)
            printf("%lld\n", query(b) - query(a - 1));
        else
            add(a, b);
    }
    return 0;
}

线段树

cpp 复制代码
#include <cstdio>
#define LL long long

const LL N = 100010;
LL n, m, a[N];
struct
{
    LL l;
    LL r;
    LL sum;
}
tr[4 * N];

void pushup(LL u)
{
    tr[u].sum = tr[u << 1].sum + tr[u << 1 | 1].sum;
}

void build(LL u, LL l, LL r)
{
    if (l == r)
        tr[u] = {l, r, a[l]};
    else
    {
        tr[u] = {l, r};
        int mid = l + r >> 1;
        build(u << 1, l, mid);
        build(u << 1 | 1, mid + 1, r);
        pushup(u);
    }
}

void modify(LL u, LL x, LL y)
{
    if (tr[u].l == tr[u].r)
        tr[u].sum += y;
    else
    {
        int mid = tr[u].l + tr[u].r >> 1;
        if (tr[u].l <= x && x <= mid)  modify(u << 1, x, y);
        else modify(u << 1 | 1, x, y);
        pushup(u);
    }
}

LL query(LL u, LL l, LL r)
{
    LL sum = 0;
    if (l <= tr[u].l && tr[u].r <= r)
        sum += tr[u].sum;
    else
    {
        int mid = tr[u].l + tr[u].r >> 1;
        if (l <= mid)  sum += query(u << 1, l, r);
        if (mid + 1 <= r)  sum += query(u << 1 | 1, l, r);
    }
    return sum;
}

int main()
{
    scanf("%lld%lld", &n, &m);
    for (LL i = 1; i <= n; i ++ )
        scanf("%lld", &a[i]);
    
    build(1, 1, n);
    while (m -- )
    {
        LL k, a, b;
        scanf("%lld%lld%lld", &k, &a, &b);
        if (!k)
            printf("%lld\n", query(1, a, b));
        else
            modify(1, a, b);
    }
    return 0;
}
相关推荐
在爪洼山玩泥巴27 分钟前
fastjson2 JSONPath 取不存在路径,为什么会抛 “not support”?
java·开发语言·jsonpath·fastjson
星落梦生10 小时前
SpringAOP基础笔记(7)
java·开发语言
我不会插花弄玉11 小时前
13.多路转接epoll【由浅入深-网络】
网络·c++·epoll
曹牧12 小时前
Java:“刷新雪崩”
java·开发语言
郝学胜-神的一滴13 小时前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
西西弗Sisyphus13 小时前
C++ explicit 关键字工程实践
开发语言·c++
郝学胜-神的一滴15 小时前
Effective Python 条款35:用类封装替代生成器异常注入
开发语言·人工智能·python·金融·pandas·scikit-learn·matplotlib
feixing_fx15 小时前
原始类型与引用类型:赋值时到底复制了什么
开发语言·前端·javascript·前端框架
wuyk55515 小时前
Python办公自动化-第02讲-Excel文件认知与四大库选型
开发语言·python·excel
AIgorithmGEEK16 小时前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set