树状数组

  first:

    单点修改,区间查询:

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
#define maxn 500005
int tree[maxn],n,m;
int lowbit(int x)
{
    return x & (-x);
}
void update(int x,int k)
{
    while(x<=n)
    {
        tree[x]+=k;
        x+=lowbit(x);
    }
}
int query(int x)
{
    int ans=0;
    while(x)
    {
        ans+=tree[x];
        x-=lowbit(x);
    }
    return ans;
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1; i<=n; i++)
    {
        int x;
        scanf("%d",&x);
        update(i,x);
    }
    for(int i=1; i<=m; i++)
    {
        int op,x,y;
        scanf("%d%d%d",&op,&x,&y);
        if(op==1)
            update(x,y);
        else
            printf("%d
",query(y)-query(x-1));
    }
    return 0;
}

  second:

   区间修改,单点查询:

#include<cstdio>
#include<iostream>
using namespace std;
#define maxn 5000005
int tree[maxn],n,m;
int lowbit(int x)
{
    return x & (-x);
}
void update(int x,int k)
{
    while(x<=n)
    {
        tree[x]+=k;
        x+=lowbit(x);
    }
}
int query(int x)
{
    int ans=0;
    while(x)
    {
        ans+=tree[x];
        x-=lowbit(x);
    }
    return ans;
}
int main()
{
    scanf("%d%d",&n,&m);
    int last=0;
    for(int i=1; i<=n; i++)
    {
        int x;
        scanf("%d",&x);
        update(i,x-last);
        last=x;
    }
    for(int i=1; i<=m; i++)
    {
        int op;
        int x,y,k;
        scanf("%d",&op);
        if(op==1)
        {
            scanf("%d%d%d",&x,&y,&k);
            update(x,k);
            update(y+1,-k);
        }
        else
        {
            scanf("%d",&x);
            printf("%d
",query(x));
        }
    }
    return 0;
}

    

原文地址:https://www.cnblogs.com/popo-black-cat/p/10343157.html