Skip to content

Commit fdc47a4

Browse files
authored
Merge pull request #4121 from brebenelmihnea/Horrible-Queries
Horrible Queries Code
2 parents 1220dd2 + 7d0604c commit fdc47a4

File tree

1 file changed

+71
-9
lines changed

1 file changed

+71
-9
lines changed

content/5_Plat/RURQ.mdx

+71-9
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
id: RURQ
33
title: 'Range Update Range Query'
4-
author: Benjamin Qi
4+
author: Benjamin Qi, Mihnea Brebenel
55
prerequisites:
66
- PURS
77
description:
@@ -37,15 +37,77 @@ queries.
3737

3838
### Implementation
3939

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+
```
47108

48-
<IncompleteSection />
109+
</CPPSection>
110+
</LanguageSection>
49111

50112
### Problems
51113

0 commit comments

Comments
 (0)