樹狀陣列的區間加法(差分)
阿新 • • 發佈:2018-12-03
應用差分原理,實現樹狀陣列區間加法
差分:a區間[1, 2, 3, 4, 5],則差分割槽間為[1, 1, 1, 1, 1]即bn = an - an-1,an = b1 +…+ bn
如果對區間[2, 4]都加上2,則a[1, 5, 6, 7, 5], 差分割槽間[1, 4, 1, 1, -2],區間增加時只需修改差分割槽間的左端點的值和右端點右邊的值
#include<bits/stdc++.h> using namespace std; typedef long long ll; int main() { ios::sync_with_stdio(false); cin.tie(0); int n, m, op; ll x, y, k; cin >> n >> m; vector<ll> tre((n << 1) + 5); vector<ll> a(n + 1), b(n + 1); function<void(int, ll)> update = [&](int pos, ll val) { while(pos <= n) { tre[pos] += val; pos += pos & -pos; } return; }; function<ll(int)> query = [&](int pos) { ll ret = 0; while(pos) { ret += tre[pos]; pos -= pos & -pos; } return ret; }; ll last = 0, now; for(int i = 1; i <= n; i++) { cin >> now; update(i, now - last); last = now; } while(m--) { cin >> op; if(op == 1) { cin >> x >> y >> k; update(x, k); update(y + 1, -k); } else { cin >> x; cout << query(x) << '\n'; } } }