Kattis - Fenwick Tree(树状数组区间更新单点求值)

Fenwick Tree

Input

The first line of input contains two integers NN, QQ, where 1N50000001≤N≤5000000 is the length of the array and 0Q50000000≤Q≤5000000 is the number of operations. Then follow QQ lines giving the operations. There are two types of operations:

  • iδδ” indicates that a[i]a[i] is incremented by δδ, where 0i<N0≤i<N and 109δ109−109≤δ≤109 (both are integers)

  • ii” is a query for the value of a[0]+a[1]++a[i1]a[0]+a[1]+…+a[i−1], where 0iN0≤i≤N (for i=0i=0 this is interpreted as an empty sum)

Output

For each query in the input, output one line giving the answer to that query.

Sample Input 1Sample Output 1
10 4
+ 7 23
? 8
+ 3 17
? 8
23
40
Sample Input 2Sample Output 2
5 4
+ 0 -43
+ 4 1
? 0
? 5
0
-42

题意

N个数,Q个询问,+i表示a[i] +一个数,?i表示询问a[0] ~ a[i-1]的和

思路

放上树状数组模板

代码

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 5000010 ;
int N,Tree[MAXN];
#define LL long long
LL a[MAXN]; 
LL lowbit(LL p) { return (p&-p); }
LL sum(LL p) {
    LL ret = 0;
    while (p> 0) ret+=a[p], p-=lowbit(p);
    return ret;
}
void add(LL p, LL v) { // 若要减去,则v传入一个负数
    while (p <= N) a[p]+=v, p+=lowbit(p);
}
int main(){
    while(cin>>N){
    int t;
    cin>>t;
    memset(Tree,0,sizeof(Tree));
    for(int i=1;i<=t;i++){
        char ch;
        int a,b;
        cin>>ch;
        if(ch=='+'){
            cin>>a>>b;
            add(a+1,b);
        }
        else{
            cin>>a;
            cout<<sum(a)<<endl;    
        }
    }
}
    return 0;
}

 

 

转载于:https://www.cnblogs.com/zhien-aa/p/6285900.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值