|
1 | 1 | ---
|
2 | 2 | id: RURQ
|
3 | 3 | title: 'Range Update Range Query'
|
4 |
| -author: Benjamin Qi |
| 4 | +author: Benjamin Qi, Mihnea Brebenel |
5 | 5 | prerequisites:
|
6 | 6 | - PURS
|
7 | 7 | description:
|
@@ -37,15 +37,77 @@ queries.
|
37 | 37 |
|
38 | 38 | ### Implementation
|
39 | 39 |
|
40 |
| -<Resources> |
41 |
| - <Resource |
42 |
| - source="Benq" |
43 |
| - title="BITrange" |
44 |
| - url="https://github.com/bqi343/USACO/blob/master/Implementations/content/data-structures/1D%20Range%20Queries%20(9.2)/BITrange.h" |
45 |
| - /> |
46 |
| -</Resources> |
| 40 | +<LanguageSection> |
| 41 | +<CPPSection> |
| 42 | + |
| 43 | +```cpp |
| 44 | +#include <bits/stdc++.h> |
| 45 | +using namespace std; |
| 46 | + |
| 47 | +// BeginCodeSnip{BIT Code (from PURS module)} |
| 48 | +template <class T> class BIT { |
| 49 | + private: |
| 50 | + int size; |
| 51 | + vector<T> bit; |
| 52 | + vector<T> arr; |
| 53 | + |
| 54 | + public: |
| 55 | + BIT(int size) : size(size), bit(size + 1), arr(size) {} |
| 56 | + |
| 57 | + void set(int ind, T val) { add(ind, val - arr[ind]); } |
| 58 | + |
| 59 | + void add(int ind, T val) { |
| 60 | + arr[ind] += val; |
| 61 | + ind++; |
| 62 | + for (; ind <= size; ind += ind & -ind) { bit[ind] += val; } |
| 63 | + } |
| 64 | + |
| 65 | + T pref_sum(int ind) { |
| 66 | + ind++; |
| 67 | + T total = 0; |
| 68 | + for (; ind > 0; ind -= ind & -ind) { total += bit[ind]; } |
| 69 | + return total; |
| 70 | + } |
| 71 | +}; |
| 72 | +// EndCodeSnip |
| 73 | + |
| 74 | +int main() { |
| 75 | + int test_num; |
| 76 | + cin >> test_num; |
| 77 | + for (int t = 0; t < test_num; t++) { |
| 78 | + int n, q; |
| 79 | + cin >> n >> q; |
| 80 | + |
| 81 | + BIT<long long> bit_values(n), bit_count(n); |
| 82 | + for (int i = 0; i < q; i++) { |
| 83 | + int type; |
| 84 | + cin >> type; |
| 85 | + |
| 86 | + if (type == 0) { |
| 87 | + int p, q, val; |
| 88 | + cin >> p >> q >> val; |
| 89 | + |
| 90 | + // Update the 2 BITs |
| 91 | + bit_values.add(p - 1, val); |
| 92 | + bit_count.add(p - 1, val * (p - 1)); |
| 93 | + bit_values.add(q, -val); |
| 94 | + bit_count.add(q, -val * q); |
| 95 | + } else { |
| 96 | + int p, q; |
| 97 | + cin >> p >> q; |
| 98 | + cout << 1LL * bit_values.pref_sum(q) * q - |
| 99 | + bit_count.pref_sum(q) - |
| 100 | + (1LL * bit_values.pref_sum(p - 1) * (p - 1) - |
| 101 | + bit_count.pref_sum(p - 1)) |
| 102 | + << '\n'; |
| 103 | + } |
| 104 | + } |
| 105 | + } |
| 106 | +} |
| 107 | +``` |
47 | 108 |
|
48 |
| -<IncompleteSection /> |
| 109 | +</CPPSection> |
| 110 | +</LanguageSection> |
49 | 111 |
|
50 | 112 | ### Problems
|
51 | 113 |
|
|
0 commit comments