树状数组

时间:2019-09-19
本文章向大家介绍树状数组,主要包括树状数组使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
#include <iostream>
#include <cstdio>

using namespace std;

const int maxn=5e5+10;

long long a[maxn],c[maxn];

inline int lowbit(int x)
{
    return x&(-x);
}

void build(int n)
{
    for(int i=1;i<=n;i++)
    {
        for(int j=i;j<=n;j+=lowbit(j))
            c[j]+=a[i];
    }
    return ;
}

void update(int x,int k,int n)
{
    for(;x<=n;x+=lowbit(x))c[x]+=k;
}

long long query(int x)
{
    long long ans=0;
    while(x)
    {
        ans+=c[x];
        x-=lowbit(x);
    }
    return ans;
}

int main()
{
    int n,m;
    scanf("%d %d",&n,&m);
    for(int i=1;i<=n;i++)
    {
        scanf("%lld",&a[i]);
    }
    build(n);
    int op,x,y;
    while(m--)
    {
        scanf("%d %d %d",&op,&x,&y);
        if(op==1)
        {
            update(x,y,n);
        }
        else
        {
            if(x>y)
                swap(x,y);
            printf("%lld\n",query(y)-query(x-1));
        }
    }
    return 0;
}

原文地址:https://www.cnblogs.com/wyhbadly/p/11552440.html