树状数组两个模板

 修改区间求点

#include<bits/stdc++.h>
//#define int long long
#define MAX(a,b,c) max(a,max(b,c))
#define MIN(a,b,c) min(a,min(b,c))
#define pb push_back
#define fi first
#define se second
typedef long long ll;
typedef long long LL;
typedef unsigned long long ull;
typedef unsigned long long uLL;
using namespace std;
const int maxn=5e5+10;
int a[maxn];
int n;
int lowbit(int x){return x&(-x); }
void update(int x,int c)
{
    while(x)
    {
        a[x]+=c;
        x=x-lowbit(x);
    }
}
int getsum(int x)
{
    int sum=0;;
    while(x<=n)
    {
        sum+=a[x]; x+=lowbit(x);
    }return sum;
}
int main()
{
    ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    int q; cin>>n>>q;
    for(int i=1;i<=n;i++)
    {
        int x; cin>>x;  update(i,x); update(i-1,-x);
    }
    while(q--)
    {
        int x;cin>>x;
        if(x==1) { int a,b,c; cin>>a>>b>>c; update(b,c); update(a-1,-c);}
        if(x==2) { int a;     cin>>a; cout<<getsum(a)<<endl;}
    }

}
求点的值

 修改点求区间

#include<bits/stdc++.h>
#define int long long
#define MAX(a,b,c) max(a,max(b,c))
#define MIN(a,b,c) min(a,min(b,c))
#define pb push_back
#define fi first
#define se second
typedef long long ll;
typedef long long LL;
typedef unsigned long long ull;
typedef unsigned long long uLL;
using namespace std;
const int maxn=5e5+10;
const int INF=0x3f3f3f3f;
int a[maxn];
int n;
int lowbit(int x){return x&(-x); }
void update(int b,int c)
{
     while(b<=n)
     {
         a[b]+=c; b=b+lowbit(b);
     }
}
int getsum(int x)
{
    int sum=0;
    while(x)
    {
        sum+=a[x];
        x-=lowbit(x);
    }
    return sum;
}
int32_t main()
{
   int q; cin>>n>>q;
   for(int i=1;i<=n;i++)
   {
       int x; cin>>x;
       update(i,x);
   }
   while(q--)
   {
       int x,b,c;
       cin>>x>>b>>c;
       if(x==1) {update(b,c);}
       if(x==2)
       {
           cout<<getsum(c)-getsum(b-1)<<endl;
       }
   }
}
区间求值

猜你喜欢

转载自www.cnblogs.com/Andromeda-Galaxy/p/9494047.html