- Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathFenwickTree.java
422 lines (372 loc) · 13.5 KB
/
FenwickTree.java
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
packagecom.jwetherell.algorithms.data_structures;
importjava.math.BigDecimal;
importjava.math.BigInteger;
importjava.util.ArrayList;
importjava.util.List;
/**
* A Fenwick tree or binary indexed tree is a data structure providing efficient methods
* for calculation and manipulation of the prefix sums of a table of values. Fenwick trees
* primarily solve the problem of balancing prefix sum calculation efficiency with element
* modification efficiency.
* <p>
* This class is meant to be somewhat generic, all you'd have to do is extend
* the Data abstract class to store your custom data. I've included a range sum
* implementations.
* <p>
* @see <a href="https://en.wikipedia.org/wiki/Fenwick_tree">Fenwick Tree (Wikipedia)</a>
* <br>
* @author Justin Wetherell <phishman3579@gmail.com>
*/
@SuppressWarnings("unchecked")
publicclassFenwickTree<DextendsFenwickTree.Data> {
privateObject[] array;
publicFenwickTree(List<D> data) {
// Find the largest index
intn = 0;
for (Datad : data)
if (d.index > n)
n = d.index;
n = next(n+1);
array = newObject[n];
// Add the data
for (Dd : data)
update(d.index, d);
}
/**
* Stabbing query
*
* @param index
* index for query
* @return data at index.
*/
publicDquery(intindex) {
returnquery(index, index);
}
/**
* Range query
*
* @param start
* start of range (inclusive)
* @param end
* end of range (inclusive)
* @return data for range.
*/
publicDquery(intstart, intend) {
finalDe = lookup(end);
finalDs = lookup(start-1);
finalDc = (D) e.copy();
if (s != null)
c.separate(s);
returnc;
}
privateDlookup(intindex) {
index++; // tree index is 1 based
index = Math.min(array.length - 1, index);
if (index <= 0)
returnnull;
Dres = null;
while (index > 0) {
if (res == null) {
finalDdata = (D) array[index];
if (data != null)
res = (D) data.copy();
} else{
res.combined((D) array[index]);
}
index = prev(index);
}
returnres;
}
privatevoidupdate(intindex, Dvalue) {
index++; // tree index is 1 based
while (index < array.length) {
Ddata = (D) array[index];
if (data == null) {
data = (D) value.copy();
data.index = index;
array[index] = data;
} else {
data.combined(value);
}
index = next(index);
}
}
privatestaticfinalintprev(intx) {
returnx & (x - 1);
}
privatestaticfinalintnext(intx) {
return2 * x - prev(x);
}
/**
* {@inheritDoc}
*/
@Override
publicStringtoString() {
finalStringBuilderbuilder = newStringBuilder();
builder.append(FenwickTreePrinter.getString(this));
returnbuilder.toString();
}
protectedstaticclassFenwickTreePrinter {
publicstatic <DextendsFenwickTree.Data> StringgetString(FenwickTree<D> tree) {
if (tree.array.length == 0)
return"Tree has no nodes.";
finalDfirst = (D) tree.array[1];
if (first == null)
return"Tree has no nodes.";
finalStringBuilderbuilder = newStringBuilder();
builder.append("└── dummy \n");
builder.append(getString(tree, 0, tree.array.length, "", true));
returnbuilder.toString();
}
privatestatic <DextendsFenwickTree.Data> StringgetString(FenwickTree<D> tree, intstart, intend, Stringprefix, booleanisTail) {
if (end > tree.array.length || (end - start == 0))
return"";
finalStringBuilderbuilder = newStringBuilder();
finalDvalue = (D) tree.array[start];
if (value != null)
builder.append(prefix + (isTail ? "└── " : "├── ") + value + "\n");
intnext = start + 1;
finalList<Integer> children = newArrayList<Integer>(2);
while (next < end) {
children.add(next);
next = next(next);
}
for (inti = 0; i < children.size() - 1; i++)
builder.append(getString(tree, children.get(i), children.get(i+1), prefix + (isTail ? " " : "│ "), false));
if (children.size() >= 1)
builder.append(getString(tree, children.get(children.size()-1), end, prefix + (isTail ? " " : "│ "), true));
returnbuilder.toString();
}
}
publicabstractstaticclassDataimplementsComparable<Data> {
protectedintindex = Integer.MIN_VALUE;
/**
* Constructor for data at index.
*
* @param index
* of data.
*/
protectedData(intindex) {
this.index = index;
}
/**
* Clear the indices.
*/
publicvoidclear() {
index = Integer.MIN_VALUE;
}
/**
* Combined this data with the Data parameter.
*
* @param data
* to combined with.
* @return Data which represents the combination.
*/
publicabstractDatacombined(Datadata);
/**
* Separate this data with the Data parameter.
*
* @param data
* to separate with.
* @return Data which represents the combination.
*/
publicabstractDataseparate(Datadata);
/**
* Deep copy of data.
*
* @return deep copy.
*/
publicabstractDatacopy();
/**
* Query inside this data object.
*
* @param startOfRange
* of range to query for.
* @param endOfRange
* of range to query for.
* @return Data queried for or NULL if it doesn't match the query.
*/
publicabstractDataquery(longstartOfRange, longendOfRange);
/**
* {@inheritDoc}
*/
@Override
publicStringtoString() {
finalStringBuilderbuilder = newStringBuilder();
builder.append("[").append(index).append("]");
returnbuilder.toString();
}
/**
* {@inheritDoc}
*/
@Override
publicintcompareTo(Datad) {
if (this.index < d.index)
return -1;
if (d.index < this.index)
return1;
return0;
}
/**
* Data structure representing sum of the range.
*/
publicstaticfinalclassRangeSumData<NextendsNumber> extendsData {
publicNsum = null;
publicRangeSumData(intindex, Nnumber) {
super(index);
this.sum = number;
}
/**
* {@inheritDoc}
*/
@Override
publicvoidclear() {
super.clear();
sum = null;
}
/**
* {@inheritDoc}
*/
@Override
publicDatacombined(Datadata) {
RangeSumData<N> q = null;
if (datainstanceofRangeSumData) {
q = (RangeSumData<N>) data;
this.combined(q);
}
returnthis;
}
/**
* {@inheritDoc}
*/
@Override
publicDataseparate(Datadata) {
RangeSumData<N> q = null;
if (datainstanceofRangeSumData) {
q = (RangeSumData<N>) data;
this.separate(q);
}
returnthis;
}
/**
* Combined range sum data.
*
* @param data
* resulted from combination.
*/
privatevoidcombined(RangeSumData<N> data) {
if (this.sum == null && data.sum == null)
return;
elseif (this.sum != null && data.sum == null)
return;
elseif (this.sum == null && data.sum != null)
this.sum = data.sum;
else {
/* TODO: This is ugly and how to handle number overflow? */
if (this.suminstanceofBigDecimal || data.suminstanceofBigDecimal) {
BigDecimalresult = ((BigDecimal)this.sum).add((BigDecimal)data.sum);
this.sum = (N)result;
} elseif (this.suminstanceofBigInteger || data.suminstanceofBigInteger) {
BigIntegerresult = ((BigInteger)this.sum).add((BigInteger)data.sum);
this.sum = (N)result;
} elseif (this.suminstanceofLong || data.suminstanceofLong) {
Longresult = (this.sum.longValue() + data.sum.longValue());
this.sum = (N)result;
} elseif (this.suminstanceofDouble || data.suminstanceofDouble) {
Doubleresult = (this.sum.doubleValue() + data.sum.doubleValue());
this.sum = (N)result;
} elseif (this.suminstanceofFloat || data.suminstanceofFloat) {
Floatresult = (this.sum.floatValue() + data.sum.floatValue());
this.sum = (N)result;
} else {
// Integer
Integerresult = (this.sum.intValue() + data.sum.intValue());
this.sum = (N)result;
}
}
}
/**
* Separate range sum data.
*
* @param data
* resulted from combination.
*/
privatevoidseparate(RangeSumData<N> data) {
if (this.sum == null && data.sum == null)
return;
elseif (this.sum != null && data.sum == null)
return;
elseif (this.sum == null && data.sum != null)
this.sum = data.sum;
else {
/* TODO: This is ugly and how to handle number overflow? */
if (this.suminstanceofBigDecimal || data.suminstanceofBigDecimal) {
BigDecimalresult = ((BigDecimal)this.sum).subtract((BigDecimal)data.sum);
this.sum = (N)result;
} elseif (this.suminstanceofBigInteger || data.suminstanceofBigInteger) {
BigIntegerresult = ((BigInteger)this.sum).subtract((BigInteger)data.sum);
this.sum = (N)result;
} elseif (this.suminstanceofLong || data.suminstanceofLong) {
Longresult = (this.sum.longValue() - data.sum.longValue());
this.sum = (N)result;
} elseif (this.suminstanceofDouble || data.suminstanceofDouble) {
Doubleresult = (this.sum.doubleValue() - data.sum.doubleValue());
this.sum = (N)result;
} elseif (this.suminstanceofFloat || data.suminstanceofFloat) {
Floatresult = (this.sum.floatValue() - data.sum.floatValue());
this.sum = (N)result;
} else {
// Integer
Integerresult = (this.sum.intValue() - data.sum.intValue());
this.sum = (N)result;
}
}
}
/**
* {@inheritDoc}
*/
@Override
publicDatacopy() {
returnnewRangeSumData<N>(index, sum);
}
/**
* {@inheritDoc}
*/
@Override
publicDataquery(longstartOfQuery, longendOfQuery) {
if (endOfQuery < this.index || startOfQuery > this.index)
returnnull;
returncopy();
}
/**
* {@inheritDoc}
*/
@Override
publicinthashCode() {
return31 * (int)(this.index + this.sum.hashCode());
}
/**
* {@inheritDoc}
*/
@Override
publicbooleanequals(Objectobj) {
if (!(objinstanceofRangeSumData))
returnfalse;
RangeSumData<N> data = (RangeSumData<N>) obj;
if (this.index == data.index && this.sum.equals(data.sum))
returntrue;
returnfalse;
}
/**
* {@inheritDoc}
*/
@Override
publicStringtoString() {
StringBuilderbuilder = newStringBuilder();
builder.append(super.toString()).append(" ");
builder.append("sum=").append(sum);
returnbuilder.toString();
}
}
}
}