Advertisement
Araf_12

Binary_Index_Tree

Apr 17th, 2025
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. const int MAXINDEX = 100005;
  6. int tree[MAXINDEX]; // BIT array
  7.  
  8. // Point update for BIT (add val to index idx)
  9. void update(int idx, int val) {
  10.     while (idx < MAXINDEX) {
  11.         tree[idx] += val;
  12.         idx += (idx & -idx);
  13.     }
  14. }
  15.  
  16. // Range update: add val to range [l, r]
  17. void range_update(int l, int r, int val) {
  18.     update(l, val);       // Add val at start
  19.     update(r + 1, -val);  // Remove val after end
  20. }
  21.  
  22. // Point query: get value at index idx
  23. int point_query(int idx) {
  24.     int res = 0;
  25.     while (idx > 0) {
  26.         res += tree[idx];
  27.         idx -= (idx & -idx);
  28.     }
  29.     return res;
  30. }
  31.  
  32. // Example usage
  33. int main() {
  34.     // Range updates
  35.     range_update(2, 5, 10);  // add 10 to all elements in [2, 5]
  36.     range_update(4, 7, 5);   // add 5 to all elements in [4, 7]
  37.  
  38.     // Point queries
  39.     cout << "Value at index 3: " << point_query(3) << endl;  // should print 10
  40.     cout << "Value at index 5: " << point_query(5) << endl;  // should print 15
  41.     cout << "Value at index 7: " << point_query(7) << endl;  // should print 5
  42.     cout << "Value at index 1: " << point_query(1) << endl;  // should print 0
  43.  
  44.     return 0;
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement