Loading

树状数组

树状数组

支持单点修改,区间查询。

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

ll c[500002], n, m;

void add(ll x, ll y) //单点修改
{
    for (; x <= n; x += lowbit(x))
        c[x] += y;
}

ll sum(ll x) //前缀和
{
    ll ans = 0;
    for (; x; x -= lowbit(x))
        ans += c[x];
    return ans;
}

ll ask(ll l, ll r) //区间查询
{
    return sum(r) - sum(l - 1);
}

int main()
{
    n = read();
    m = read();
    for (int i = 1; i <= n; ++i) //初始化
    {
        ll x = read();
        add(i, x);
    }
    for (int i = 1; i <= m; ++i)
    {
        ll opt = read();
        if (opt == 1) //单点修改
        {
            ll x = read(), k = read();
            add(x, k);
        }
        else if (opt == 2) //区间查询
        {
            ll x, y;
            x = read();
            y = read();
            ll ans = ask(x, y);
            printf("%lld\n", ans);
        }
    }
    return 0;
}
posted @ 2021-06-29 09:54  EdisonBa  阅读(23)  评论(0编辑  收藏  举报