树状数组1:
#include <iostream>
using namespace std;
const int maxn = 500001;
int sum[maxn];
int n, m;
int lowbit(int x){
return x & (-x);
}
int getsum(int pos){
int ret = 0;
while(pos > 0){
ret += sum[pos];
pos -= lowbit(pos); // 不断的找到子节点
}
return ret;
}
void add(int pos, int num){
while(pos <= n){
sum[pos] += num;
pos += lowbit(pos); // 不断的找到父节点进行更新
}
}
void solve(){
cin >> n >> m;
for(int i = 1; i <= n; ++i){
int num; cin >> num;
add(i, num);
}
for(int i = 0; i < m; ++i){
int choose, x, y;
cin >> choose >> x >> y;
if(choose == 1) add(x, y);
else cout << getsum(y) - getsum(x - 1) << '\n';
}
}
int main(){
solve();
return 0;
}
树状数组2(差分约束):
#include <iostream>
using namespace std;
const int maxn = 500001;
int a[maxn];
int sum[maxn];
int n, m;
int lowbit(int x){
return x & (-x);
}
int getsum(int pos){
int ret = 0;
while(pos != 0){
ret += sum[pos];
pos -= lowbit(pos); // 不断的找到子节点
}
return ret;
}
void add(int pos, int num){
while(pos <= n){
sum[pos] += num;
pos += lowbit(pos); // 不断的找到父节点进行更新
}
}
int search_(int pos){
int ans = 0;
while(pos != 0){
ans += sum[pos];
pos -= lowbit(pos);
}
return ans;
}
void solve(){
cin >> n >> m;
int a1 = 0;
for(int i = 1; i <= n; ++i){
int a2; cin >> a2;
add(i, a2 - a1); // 差分约束
a1 = a2;
}
for(int i = 0; i < m; ++i){
int choose, x, y, k;
cin >> choose;
if(choose == 1){
cin >> x >> y >> k;
add(x, k); add(y + 1, -k); // 差分约束
}
else{
cin >> x;
cout << search_(x) << '\n';
}
}
}
int main(){
solve();
return 0;
}