Skip to content

Instantly share code, notes, and snippets.

@NamPE286
Last active November 22, 2022 15:52
Show Gist options
  • Save NamPE286/5cf6d94696e6d9ca22528f3e4ce984ec to your computer and use it in GitHub Desktop.
Save NamPE286/5cf6d94696e6d9ca22528f3e4ce984ec to your computer and use it in GitHub Desktop.
Binary Indexed Tree (Fenwick Tree) C++ implementation for range update, point query
// https://cses.fi/problemset/task/1651/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct BIT{
//1-indexed
vector<ll> bit;
ll n;
BIT(ll N){
n = N;
bit = vector<ll>(2*n + 1);
}
ll get(ll i) { //get sum with prefix sum array, get single value with difference array
ll ans = 0;
while (i > 0) {
ans += bit[i];
i -= (i & (-i));
}
return ans;
}
void updateSingle(ll i, ll val) {
while (i <= n) {
bit[i] += val; // change += to = or -= to change update mode
i += (i & (-i));
}
}
void updateRange(ll l, ll r, ll val) {
updateSingle(l, val);
updateSingle(r + 1, -val);
}
};
int main(){
ll n, q;
cin >> n >> q;
BIT a(n);
ll diff = 0;
for(ll i = 1; i <= n; i++){
ll x;
cin >> x;
a.updateSingle(i, x - diff);
diff = x;
}
while(q--){
ll type;
cin >> type;
if (type == 1) {
ll l, r, v;
cin >> l >> r >> v;
a.updateRange(l, r, v);
} else if (type == 2) {
ll i;
cin >> i;
cout << a.get(i) << '\n';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment