#include <iostream>
#include <algorithm>
#include <cstdio>
#define ll long long int
using namespace std;
ll c[1000000];
ll lowbit(ll x)
{
return x&(-x);
}
void add(ll x,ll y,ll n)
{
for(ll i=x;i<=n;i+=lowbit(i))
c[i]+=y;
}
ll query(ll x)
{
ll ans=0;
for(ll i=x;i>=1;i-=lowbit(i))
ans+=c[i];
return ans;
}
int main()
{
ll i,j,n,m,k,x,y,z;
cin >> n >> m;
for(i=1;i<=n;i++)
{
cin >> x;
add(i,x,n);
}
for(i=1;i<=m;i++)
{
cin >> x >> y >> z;
if(x==1)
{
add(y,z,n);
}
else
{
cout << query(z)-query(y-1) << endl;
}
}
return 0;
}
详细过程;大佬blog
区间最大值:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#define maxn 200005
#define ll long long int
using namespace std;
ll n,m;
ll tree[maxn],a[maxn];
inline ll lowbit(ll x)
{
return x&(-x);
}
inline void add(ll x)
{
while(x<=n)
{
tree[x]=a[x];
for(ll i=1;i<lowbit(x);i<<=1)
tree[x]=max(tree[x],tree[x-1]);
x+=lowbit(x);
}
return ;
}
inline ll sum(ll x,ll y)
{
ll ans=0;
while(y>=x)
{
ans=max(ans,tree[y]);
y--;
for(;y-lowbit(y)>=x;y-=lowbit(y))
ans=max(ans,tree[y]);
}
return ans;
}
int main()
{
ll i,j,k,x,y,s;
while(~scanf("%lld %lld",&n,&m))
{
for(i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
add(i);
}
for(i=1;i<=m;i++)
{
scanf("%lld %lld",&x,&y);
s=sum(x,y);
cout << s << endl;
}
}
return 0;
}