树状数组模板

链接:https://www.nowcoder.com/acm/contest/77/B
来源:牛客网

题目描述

给一个数列,会有多次询问,对于每一次询问,会有两种操作:
1:给定两个整数x, y, 然后在原数组的第x位置上加y;
2:给定两个整数l,r,然后输出数组从第l位加到第r位数字的和并换行

输入描述:

第一行有两个整数n, m(1 <= n, m <= 100000)代表数列的长度和询问的次数
第二行n个数字,对于第i个数字a[i],(0<=a[i]<=100000)。
接下来m行,每一行有三个整数f, x, y。第一个整数f是1或者是2,代表操作类型,如果是1,接下来两个数x,y代表第x的位置上加y,如果是2,则求x到y的和,保证数据合法。

输出描述:

输出每次求和的结果并换行
示例1

输入

10 2
1 2 3 4 5 6 7 8 9 10
1 1 9
2 1 10

输出

64
#include <bits/stdc++.h>
using namespace std;
typedef long long  ll;
const int INF = 0x3f3f3f3f;
const int moder = 10000;
const int maxn = 2000000;
int d[100010];
int n;
int lowbit(int x)
{
    return x&(-x);
}

int query(int x) //查询前缀和
{
    int res = 0;
    while(x)
    {
        res += d[x];
        x -= lowbit(x);
    }
    return res;
}

void add(int x,int v)//单点修改
{
    while(x <= n)
    {
        d[x] += v;
        x += lowbit(x);
    }
}

int main()
{
    int m;
    cin >> n >> m;
    memset(d,0,sizeof(d));
    for(int i=1;i <= n;i++)
    {
        int x;
        scanf("%d",&x);
        add(i,x);
    }
    for(int i=0;i < m;i++)
    {
        int f,x,y;
        scanf("%d%d%d",&f,&x,&y);
        if(f == 1) add(x,y);
        else printf("%d
",query(y)-query(x-1));
    }
    return 0;
}

———https://www.bilibili.com/video/av18735440/?from=search&seid=16259403139038048644

原文地址:https://www.cnblogs.com/cunyusup/p/8476448.html