树状数组和线段树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;
}
相关推荐
吴可可1238 小时前
Win7上开发CAD2004自定义实体全解析
c++·算法
孟华苏8 小时前
怎么快速排查内存泄漏问题
java·开发语言·python
zz34572981138 小时前
C语言中字符串常量存储位置
c语言·开发语言·算法·青少年编程
noipp8 小时前
推荐题目:洛谷 P16510 [GKS 2015 #C] gRanks
java·c语言·开发语言·c++·python·算法
flyinmind8 小时前
Java环境与Android环境中使用QuickJS
java·开发语言·javascript·quickjs
郑洁文8 小时前
基于Python的HTTP服务漏洞信息收集工具设计与实现
开发语言·python·http
程序喵大人8 小时前
从内存/汇编角度看C与C++:指针、引用、对象的底层差异
c语言·汇编·c++·指针·引用·对象
不吃鱼的羊8 小时前
DaVinci Developer自动连接
java·开发语言
Evand J8 小时前
【MATLAB例程】VSIMM与IMM在机动目标跟踪中的性能对比,CV+CT双模型
开发语言·matlab·目标跟踪
Meteors.8 小时前
Kotlin协程序使用技巧和应用场景
android·开发语言·kotlin