SHARE
    TWEET
    Araf_12

    Binary_Index_Tree

    Apr 17th, 2025
    418
    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. const int MAXINDEX = 100005;
    5. int tree[MAXINDEX]; // BIT array
    6. // Point update for BIT (add val to index idx)
    7. void update(int idx, int val) {
    8. while (idx < MAXINDEX) {
    9. tree[idx] += val;
    10. idx += (idx & -idx);
    11. }
    12. }
    13. // Range update: add val to range [l, r]
    14. void range_update(int l, int r, int val) {
    15. update(l, val); // Add val at start
    16. update(r + 1, -val); // Remove val after end
    17. }
    18. // Point query: get value at index idx
    19. int point_query(int idx) {
    20. int res = 0;
    21. while (idx > 0) {
    22. res += tree[idx];
    23. idx -= (idx & -idx);
    24. }
    25. return res;
    26. }
    27. // Example usage
    28. int main() {
    29. // Range updates
    30. range_update(2, 5, 10); // add 10 to all elements in [2, 5]
    31. range_update(4, 7, 5); // add 5 to all elements in [4, 7]
    32. // Point queries
    33. cout << "Value at index 3: " << point_query(3) << endl; // should print 10
    34. cout << "Value at index 5: " << point_query(5) << endl; // should print 15
    35. cout << "Value at index 7: " << point_query(7) << endl; // should print 5
    36. cout << "Value at index 1: " << point_query(1) << endl; // should print 0
    37. return 0;
    38. }
    Advertisement
    Add Comment
    Please, Sign In to add comment
    Public Pastes
    We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
    Not a member of Pastebin yet?
    Sign Up, it unlocks many cool features!

    AltStyle によって変換されたページ (->オリジナル) /