樹狀陣列【模板】
阿新 • • 發佈:2018-12-20
樹狀陣列
程式碼如下:
#include <iostream>
#include <cstdio>
using namespace std;
const int N = 500005;
int a[N],c[N],n,m,k,x,y;
int lowbit(int i)
{
return i & (-i);
}
int add(int loc,int value)
{
for(int i = loc; i <= n; i += lowbit(i))
c[i] += value;
return 0;
}
int query(int loc)
{
int sum = 0;
for(int i = loc; i > 0; i -= lowbit(i))
sum += c[i];
return sum ;
}
int main()
{
scanf("%d%d",&n,&m);
for(int i = 1; i <= n; i ++)
scanf("%d",&a[i]);
for(int i = 1; i <= n; i ++)
for(int j = i-lowbit(i)+1;j <= i; j ++)
c[i] += a[j];
while(m --)
{
scanf ("%d%d%d",&k,&x,&y);
if(k == 1)
{
add(x,y);
}
if(k == 2)
{
int ans = query(y) - query(x-1);
printf("%d\n",ans);
}
}
return 0;
}