[luogu 3374]树状数组1【模板】

版权声明:请大家斧正,如喜欢的话,为拙见点一个赞吧。 https://blog.csdn.net/qq_39897867/article/details/81940907

题目

https://www.luogu.org/problemnew/show/P3374


解题思路

对于树状数组,我在此之前并没有敲过一道题。现在做的两道题([poj 3468]A Simple Problem with Integers & [ch 4201] 楼兰图腾{树状数组(逆序对)})都是糊里糊涂的。

所以我便做了两道树状数组模板,加深对树状数组的理解。!!!

关于树状数组的,转载至(通俗易懂):


代码

#include<cstdio>
using namespace std; 
int n,m,t,x,y,a[2000001]; 
void add(int x,int y) {for (;x<=n;x+=x&-x) a[x]+=y; }
int answer(int x){
    int ans=0; 
    for (;x;x-=x&-x) ans+=a[x]; 
    return ans; 
}
int main()
{
    scanf("%d%d",&n,&m); 
    for (int i=1;i<=n;i++) scanf("%d",&t),add(i,t); 
    for (int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&t,&x,&y); 
        if (t==1) add(x,y); else printf("%d\n",answer(y)-answer(x-1)); 
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39897867/article/details/81940907