树状数组

#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
",query(y)-query(x-1));
        }
    }
    return 0;
}
单点修改
#include <iostream>
#include <cstdio>

using namespace std;

const int maxn=5e5+10;

long long a[maxn],c[maxn],b[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",&b[i]);
        a[i]=b[i]-b[i-1];
    }
    build(n);
    int op,x,y,k;
    while(m--)
    {
        scanf("%d %d",&op,&x);
        if(op==1)
        {
            scanf("%d %d",&y,&k);
            update(x,k,n);
            update(y+1,-k,n);
        }
        else
        {
            printf("%lld
",query(x));
        }
    }
    return 0;
}
区间修改,单点查询
原文地址:https://www.cnblogs.com/wyhbadly/p/11552440.html