树状数组模板

一、区间求和


#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
typedef long long ll;
using namespace std;
const int maxn=50010;
ll N,army[maxn];

ll lowbit(ll k)
{
    return k&(-k);
}
void modify(ll x,ll add)//更新操作
{
    while(x<=N)
    {
        army[x]+=add;
        x+=lowbit(x);
    }
}
 ll get_sum(ll x)//区间求和
{
    ll ret=0;
    while(x>0)
    {
        ret+=army[x];
        x-=lowbit(x);
    }
    return ret;
}

int main()
{
    scanf("%lld",&N);
    ll d;
    for(int i=1;i<=N;i++)
    {
        scanf("%lld",&d);
        modify(i,d);
    }
    long long q;
    scanf("%lld",&q);
    ll s,l;
    while(q--)
    {
        scanf("%lld%lld",&s,&l);
        printf("%lld
",get_sum(l+s-1)-get_sum(s-1));
        //printf("%d
",);
    }
    return 0;

}




原文地址:https://www.cnblogs.com/bryce1010/p/9387135.html