树状数组(板子)

树状数组,

1,单点修改,区间查询;例题

code:

主要操作:

int lowbit(int x)
{
    return x&(-x);
}
void build(int x,int k)
{
    for(int i=x; i<=n; i+=lowbit(i))
      tree[i]+=k;
}
int quary(int x)
{
    int ans=0;
    for(int i=x; i>=1; i-=lowbit(i))
     ans+=tree[i];
    return ans;
}
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=5e5+10;
int a[maxn],tree[maxn];
int n,m;
int lowbit(int x)
{
    return x&(-x);
}
void build(int x,int k)
{
    for(int i=x; i<=n; i+=lowbit(i))
      tree[i]+=k;
}
int quary(int x)
{
    int ans=0;
    for(int i=x; i>=1; i-=lowbit(i))
     ans+=tree[i];
    return ans;
}
int main()
{
    cin>>n>>m;
    for(int i=1; i<=n; i++) 
    {
        cin>>a[i];
        build(i,a[i]);
    }
    while(m--)
    {
        int k,x,y;
        cin>>k>>x>>y;
        if(k==1)
         build(x,y);
        else
        {
            cout<<quary(y)-quary(x-1)<<endl;
        }  
    }
    //system("pause");
    return 0;
}
 

2,区间修改,单点查询:(差分思想)例题:

      if(k==1)
         {
             cin>>y>>z;
             build(x,z);
             build(y+1,-z);
         }
        else
        {
            cout<<a[x]+quary(x)<<endl;
        }  
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

const int maxn=5e5+10;
ll a[maxn],tree[maxn];
ll n,m;
ll lowbit(ll x)
{
    return x&(-x);
}
void build(ll x,ll k)
{
    for(ll i=x; i<=n; i+=lowbit(i))
      tree[i]+=k;
}
ll quary(ll x)
{
    ll ans=0;
    for(ll i=x; i>=1; i-=lowbit(i))
     ans+=tree[i];
    return ans;
}
int main()
{
    cin>>n>>m;
    for(int i=1; i<=n; i++) 
    {
        cin>>a[i];
    }
    while(m--)
    {
        ll k,x,y,z;
        cin>>k>>x;
        if(k==1)
         {
             cin>>y>>z;
             build(x,z);

             build(y+1,-z);

         }
        else
        {
            cout<<a[x]+quary(x)<<endl;
        }  
    }
    //system("pause");
    return 0;
}
原文地址:https://www.cnblogs.com/sweetlittlebaby/p/12748553.html