洛谷 P3374 【模板】树状数组 1(树状数组模板题)

发布时间 2023-03-27 20:42:59作者: 高尔赛凡尔娟

https://www.luogu.com.cn/problem/P3374

题目大意:

有一个数组a,有两种操作:

一种是在x的位置上添加y;
一种是输出x到y位置上所有数字的和。
输入 #1 
5 5
1 5 4 2 3
1 1 3
2 2 5
1 3 -1
1 4 2
2 1 4
输出 #1 
14
16
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL,LL> PII;
const LL MAXN=1e18,MINN=-MAXN,INF=0x3f3f3f3f;
const LL N=2e6+10,M=2023;
const LL mod=998244353;
const double PI=3.1415926535;
#define endl '\n'
int n,m;
int a[N],tr[N];
int lowbit(int x)
{
    return x&(-x);
}
void add(int x,int v)
{
    for(int i=x;i<=n;i+=lowbit(i))
    {
        tr[i]+=v;
    }
}
int query(int x)
{
    int res=0;
    for(int i=x;i>=1;i-=lowbit(i))
    {
        res+=tr[i];
    }
    return res;
}
int main()
{
    cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
    int T=1;
    //cin>>T;
    while(T--)
    {
        cin>>n>>m;
        for(int i=1;i<=n;i++)
        {
            cin>>a[i];
            add(i,a[i]);//初始化,默认全是0
        }
        while(m--)
        {
            int op;
            cin>>op;
            if(op==1)
            {
                LL x,k;
                cin>>x>>k;
                add(x,k);//x的下标处加上k
            }
            else if(op==2)
            {
                LL x,y;
                cin>>x>>y;
                cout<<query(y)-query(x-1)<<endl;//求和从x到y
            }
        }
    }
    return 0;
}