-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfenwick_tree.cpp
More file actions
334 lines (294 loc) · 11.3 KB
/
fenwick_tree.cpp
File metadata and controls
334 lines (294 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/*
Fenwick Tree (Binary Indexed Tree)
Mathematical Foundation: Tree structure using bit manipulation
LSB(i) = i & (-i), parent[i] = i - LSB(i), next[i] = i + LSB(i)
Range sum query: O(log n), Point update: O(log n)
Space: O(n), 1-indexed for easier implementation
*/
#include <bits/stdc++.h>
using namespace std;
// Basic Fenwick Tree (Point Update, Range Query)
// Related LeetCode Problems:
// 307. Range Sum Query - Mutable
// https://leetcode.com/problems/range-sum-query-mutable/
// 315. Count of Smaller Numbers After Self
// https://leetcode.com/problems/count-of-smaller-numbers-after-self/
// 327. Count of Range Sum
// https://leetcode.com/problems/count-of-range-sum/
// 493. Reverse Pairs
// https://leetcode.com/problems/reverse-pairs/
// 673. Number of Longest Increasing Subsequence
// https://leetcode.com/problems/number-of-longest-increasing-subsequence/
// 1395. Count Number of Teams
// https://leetcode.com/problems/count-number-of-teams/
// 1649. Create Sorted Array through Instructions
// https://leetcode.com/problems/create-sorted-array-through-instructions/
// 2179. Count Good Triplets in an Array
// https://leetcode.com/problems/count-good-triplets-in-an-array/
// 2659. Make Array Empty
// https://leetcode.com/problems/make-array-empty/
class FenwickTree {
vector<long long> tree;
int n;
public:
FenwickTree(int n) : n(n), tree(n + 1, 0) {}
FenwickTree(vector<int>& arr) : n(arr.size()), tree(n + 1, 0) {
for (int i = 0; i < n; i++)
update(i + 1, arr[i]);
}
void update(int i, long long delta) {
for (; i <= n; i += i & -i)
tree[i] += delta;
}
long long query(int i) {
long long sum = 0;
for (; i > 0; i -= i & -i)
sum += tree[i];
return sum;
}
long long rangeQuery(int l, int r) {
return query(r) - query(l - 1);
}
};
// 2D Fenwick Tree
// Related LeetCode Problems:
// 308. Range Sum Query 2D - Mutable
// https://leetcode.com/problems/range-sum-query-2d-mutable/
// 850. Rectangle Area II
// https://leetcode.com/problems/rectangle-area-ii/
// 699. Falling Squares
// https://leetcode.com/problems/falling-squares/
// 715. Range Module
// https://leetcode.com/problems/range-module/
// 1222. Queens That Can Attack the King
// https://leetcode.com/problems/queens-that-can-attack-the-king/
// 1329. Sort the Matrix Diagonally
// https://leetcode.com/problems/sort-the-matrix-diagonally/
// 1878. Get Biggest Three Rhombus Sums in a Grid
// https://leetcode.com/problems/get-biggest-three-rhombus-sums-in-a-grid/
// 2536. Increment Submatrices by One
// https://leetcode.com/problems/increment-submatrices-by-one/
class FenwickTree2D {
vector<vector<long long>> tree;
int n, m;
public:
FenwickTree2D(int n, int m) : n(n), m(m), tree(n + 1, vector<long long>(m + 1, 0)) {}
void update(int x, int y, long long delta) {
for (int i = x; i <= n; i += i & -i)
for (int j = y; j <= m; j += j & -j)
tree[i][j] += delta;
}
long long query(int x, int y) {
long long sum = 0;
for (int i = x; i > 0; i -= i & -i)
for (int j = y; j > 0; j -= j & -j)
sum += tree[i][j];
return sum;
}
long long rangeQuery(int x1, int y1, int x2, int y2) {
return query(x2, y2) - query(x1 - 1, y2) - query(x2, y1 - 1) + query(x1 - 1, y1 - 1);
}
};
// Range Update Fenwick Tree (using difference array)
// Related LeetCode Problems:
// 370. Range Addition
// https://leetcode.com/problems/range-addition/
// 598. Range Addition II
// https://leetcode.com/problems/range-addition-ii/
// 1109. Corporate Flight Bookings
// https://leetcode.com/problems/corporate-flight-bookings/
// 1094. Car Pooling
// https://leetcode.com/problems/car-pooling/
// 1526. Minimum Number of Increments on Subarrays to Form a Target Array
// https://leetcode.com/problems/minimum-number-of-increments-on-subarrays-to-form-a-target-array/
// 2251. Number of Flowers in Full Bloom
// https://leetcode.com/problems/number-of-flowers-in-full-bloom/
// 2536. Increment Submatrices by One
// https://leetcode.com/problems/increment-submatrices-by-one/
class RangeUpdateFenwick {
FenwickTree ft;
public:
RangeUpdateFenwick(int n) : ft(n) {}
void rangeUpdate(int l, int r, long long delta) {
ft.update(l, delta);
ft.update(r + 1, -delta);
}
long long pointQuery(int i) {
return ft.query(i);
}
};
// Range Update Range Query Fenwick Tree
// Related LeetCode Problems:
// 370. Range Addition
// https://leetcode.com/problems/range-addition/
// 1109. Corporate Flight Bookings
// https://leetcode.com/problems/corporate-flight-bookings/
// 1094. Car Pooling
// https://leetcode.com/problems/car-pooling/
// 1526. Minimum Number of Increments on Subarrays to Form a Target Array
// https://leetcode.com/problems/minimum-number-of-increments-on-subarrays-to-form-a-target-array/
// 2251. Number of Flowers in Full Bloom
// https://leetcode.com/problems/number-of-flowers-in-full-bloom/
// 2536. Increment Submatrices by One
// https://leetcode.com/problems/increment-submatrices-by-one/
// 1622. Fancy Sequence
// https://leetcode.com/problems/fancy-sequence/
// 2286. Booking Concert Tickets in Groups
// https://leetcode.com/problems/booking-concert-tickets-in-groups/
class RURQFenwick {
FenwickTree ft1, ft2;
int n;
public:
RURQFenwick(int n) : n(n), ft1(n), ft2(n) {}
void rangeUpdate(int l, int r, long long delta) {
ft1.update(l, delta);
ft1.update(r + 1, -delta);
ft2.update(l, delta * (l - 1));
ft2.update(r + 1, -delta * r);
}
long long prefixQuery(int i) {
return ft1.query(i) * i - ft2.query(i);
}
long long rangeQuery(int l, int r) {
return prefixQuery(r) - prefixQuery(l - 1);
}
};
// Fenwick Tree for Maximum (using coordinate compression)
// Related LeetCode Problems:
// 239. Sliding Window Maximum
// https://leetcode.com/problems/sliding-window-maximum/
// 699. Falling Squares
// https://leetcode.com/problems/falling-squares/
// 715. Range Module
// https://leetcode.com/problems/range-module/
// 732. My Calendar III
// https://leetcode.com/problems/my-calendar-iii/
// 850. Rectangle Area II
// https://leetcode.com/problems/rectangle-area-ii/
// 1353. Maximum Number of Events That Can Be Attended
// https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/
// 1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits
// https://leetcode.com/problems/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/
// 2286. Booking Concert Tickets in Groups
// https://leetcode.com/problems/booking-concert-tickets-in-groups/
class MaxFenwick {
vector<int> tree;
int n;
public:
MaxFenwick(int n) : n(n), tree(n + 1, INT_MIN) {}
void update(int i, int val) {
for (; i <= n; i += i & -i)
tree[i] = max(tree[i], val);
}
int query(int i) {
int maxVal = INT_MIN;
for (; i > 0; i -= i & -i)
maxVal = max(maxVal, tree[i]);
return maxVal;
}
};
// Inversion Count using Fenwick Tree
// Related LeetCode Problems:
// 315. Count of Smaller Numbers After Self
// https://leetcode.com/problems/count-of-smaller-numbers-after-self/
// 493. Reverse Pairs
// https://leetcode.com/problems/reverse-pairs/
// 327. Count of Range Sum
// https://leetcode.com/problems/count-of-range-sum/
// 1395. Count Number of Teams
// https://leetcode.com/problems/count-number-of-teams/
// 1649. Create Sorted Array through Instructions
// https://leetcode.com/problems/create-sorted-array-through-instructions/
// 2179. Count Good Triplets in an Array
// https://leetcode.com/problems/count-good-triplets-in-an-array/
// 2426. Number of Pairs Satisfying Inequality
// https://leetcode.com/problems/number-of-pairs-satisfying-inequality/
// 2659. Make Array Empty
// https://leetcode.com/problems/make-array-empty/
long long inversionCount(vector<int>& arr) {
vector<int> sorted = arr;
sort(sorted.begin(), sorted.end());
sorted.erase(unique(sorted.begin(), sorted.end()), sorted.end());
auto compress = [&](int x) {
return lower_bound(sorted.begin(), sorted.end(), x) - sorted.begin() + 1;
};
FenwickTree ft(sorted.size());
long long inversions = 0;
for (int i = arr.size() - 1; i >= 0; i--) {
int compressed = compress(arr[i]);
inversions += ft.query(compressed - 1);
ft.update(compressed, 1);
}
return inversions;
}
// Count smaller elements after self
// Related LeetCode Problems:
// 315. Count of Smaller Numbers After Self
// https://leetcode.com/problems/count-of-smaller-numbers-after-self/
// 493. Reverse Pairs
// https://leetcode.com/problems/reverse-pairs/
// 327. Count of Range Sum
// https://leetcode.com/problems/count-of-range-sum/
// 1395. Count Number of Teams
// https://leetcode.com/problems/count-number-of-teams/
// 1649. Create Sorted Array through Instructions
// https://leetcode.com/problems/create-sorted-array-through-instructions/
// 2179. Count Good Triplets in an Array
// https://leetcode.com/problems/count-good-triplets-in-an-array/
// 2426. Number of Pairs Satisfying Inequality
// https://leetcode.com/problems/number-of-pairs-satisfying-inequality/
// 2659. Make Array Empty
// https://leetcode.com/problems/make-array-empty/
vector<int> countSmaller(vector<int>& nums) {
vector<int> sorted = nums;
sort(sorted.begin(), sorted.end());
sorted.erase(unique(sorted.begin(), sorted.end()), sorted.end());
auto compress = [&](int x) {
return lower_bound(sorted.begin(), sorted.end(), x) - sorted.begin() + 1;
};
FenwickTree ft(sorted.size());
vector<int> result(nums.size());
for (int i = nums.size() - 1; i >= 0; i--) {
int compressed = compress(nums[i]);
result[i] = ft.query(compressed - 1);
ft.update(compressed, 1);
}
return result;
}
// Range Minimum Query using Fenwick Tree (with coordinate compression)
// Related LeetCode Problems:
// 239. Sliding Window Maximum
// https://leetcode.com/problems/sliding-window-maximum/
// 699. Falling Squares
// https://leetcode.com/problems/falling-squares/
// 715. Range Module
// https://leetcode.com/problems/range-module/
// 732. My Calendar III
// https://leetcode.com/problems/my-calendar-iii/
// 850. Rectangle Area II
// https://leetcode.com/problems/rectangle-area-ii/
// 1353. Maximum Number of Events That Can Be Attended
// https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/
// 1505. Minimum Possible Integer After at Most K Adjacent Swaps On Digits
// https://leetcode.com/problems/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/
// 2286. Booking Concert Tickets in Groups
// https://leetcode.com/problems/booking-concert-tickets-in-groups/
class RMQFenwick {
vector<int> tree;
int n;
public:
RMQFenwick(int n) : n(n), tree(n + 1, INT_MAX) {}
void update(int i, int val) {
for (; i <= n; i += i & -i)
tree[i] = min(tree[i], val);
}
int query(int i) {
int minVal = INT_MAX;
for (; i > 0; i -= i & -i)
minVal = min(minVal, tree[i]);
return minVal;
}
void reset() {
fill(tree.begin(), tree.end(), INT_MAX);
}
};