forked from phishman3579/java-algorithms-implementation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SegmentTree.java
1411 lines (1229 loc) · 49.4 KB
/
SegmentTree.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.jwetherell.algorithms.data_structures;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
* Segment tree using objects and pointers. A segment tree is a tree data
* structure for storing intervals, or segments. It allows querying which of the
* stored segments contain a given point. It is, in principle, a static
* structure; that is, its content cannot be modified once the structure is
* built.
* <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 also included a range
* minimum, range maximum, range sum, and interval stabbing implementations.
* <p>
* @see <a href="https://en.wikipedia.org/wiki/Segment_tree">Segment Tree (Wikipedia)</a>
* <br>
* @author Justin Wetherell <phishman3579@gmail.com>
*/
@SuppressWarnings("unchecked")
public abstract class SegmentTree<D extends SegmentTree.Data> {
protected Segment<D> root = null;
/**
* Stabbing query
*
* @param index
* index to query
* @return data at index.
*/
public abstract D query(long index);
/**
* Range query
*
* @param start
* start of range (inclusive)
* @param end
* end of range to (inclusive)
* @return data for range.
*/
public abstract D query(long start, long end);
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(SegmentTreePrinter.getString(this));
return builder.toString();
}
public abstract static class Data implements Comparable<Data> {
protected long start = Long.MIN_VALUE;
protected long end = Long.MAX_VALUE;
/**
* Constructor for data at index
*
* @param index
* of data.
*/
public Data(long index) {
this.start = index;
this.end = index;
}
/**
* Constructor for data at range (inclusive)
*
* @param start
* start of range for data.
* @param end
* end of range for data.
*/
public Data(long start, long end) {
this.start = start;
this.end = end;
}
/**
* Clear the indices
*/
public void clear() {
start = Long.MIN_VALUE;
end = Long.MAX_VALUE;
}
/**
* Combined this data with the Data parameter
*
* @param data
* Data to combined
* @return Data which represents the combination.
*/
public abstract Data combined(Data data);
/**
* Deep copy of data.
*
* @return deep copy.
*/
public abstract Data copy();
/**
* Query inside this data object.
*
* @param startOfRange
* start of range (inclusive)
* @param endOfRange
* end of range (inclusive)
* @return Data queried for or NULL if it doesn't match the query.
*/
public abstract Data query(long startOfRange, long endOfRange);
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append(start).append("->").append(end);
return builder.toString();
}
/**
* {@inheritDoc}
*/
@Override
public int compareTo(Data d) {
if (this.end < d.end)
return -1;
if (d.end < this.end)
return 1;
return 0;
}
/**
* Data structure representing points in the x,y space and their
* location in the quadrants.
*/
public static final class QuadrantData extends Data {
public long quad0 = 0;
public long quad1 = 0;
public long quad2 = 0;
public long quad3 = 0;
public QuadrantData(long start, long end) {
super(start, end);
}
public QuadrantData(long index, long quad1, long quad2, long quad3, long quad4) {
super(index);
this.quad0 = quad1;
this.quad1 = quad2;
this.quad2 = quad3;
this.quad3 = quad4;
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
super.clear();
quad0 = 0;
quad1 = 0;
quad2 = 0;
quad3 = 0;
}
/**
* {@inheritDoc}
*/
@Override
public QuadrantData copy() {
final QuadrantData copy = new QuadrantData(start, end);
copy.quad0 = this.quad0;
copy.quad1 = this.quad1;
copy.quad2 = this.quad2;
copy.quad3 = this.quad3;
return copy;
}
/**
* {@inheritDoc}
*/
@Override
public Data query(long startOfQuery, long endOfQuery) {
if (endOfQuery < this.start || startOfQuery > this.end)
return null;
return copy();
}
/**
* {@inheritDoc}
*/
@Override
public Data combined(Data data) {
QuadrantData q = null;
if (data instanceof QuadrantData) {
q = (QuadrantData) data;
this.combined(q);
}
return this;
}
private void combined(QuadrantData data) {
this.quad0 += data.quad0;
this.quad1 += data.quad1;
this.quad2 += data.quad2;
this.quad3 += data.quad3;
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return 31 * (int)(this.start + this.end + this.quad0 + this.quad1 + this.quad2 + this.quad3);
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof QuadrantData))
return false;
QuadrantData data = (QuadrantData) obj;
if (this.start == data.start && this.end == data.end && this.quad0 == data.quad0
&& this.quad1 == data.quad1 && this.quad2 == data.quad2 && this.quad3 == data.quad3)
{
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append(super.toString()).append(" ");
builder.append(quad0).append(",");
builder.append(quad1).append(",");
builder.append(quad2).append(",");
builder.append(quad3);
return builder.toString();
}
}
/**
* Data structure representing maximum in the range.
*/
public static final class RangeMaximumData<N extends Number> extends Data {
public N maximum = null;
public RangeMaximumData(long start, long end) {
super(start, end);
}
public RangeMaximumData(long index, N number) {
super(index);
this.maximum = number;
}
public RangeMaximumData(long start, long end, N number) {
super(start, end);
this.maximum = number;
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
super.clear();
maximum = null;
}
/**
* {@inheritDoc}
*/
@Override
public Data copy() {
return new RangeMaximumData<N>(start, end, maximum);
}
/**
* {@inheritDoc}
*/
@Override
public Data query(long startOfQuery, long endOfQuery) {
if (endOfQuery < this.start || startOfQuery > this.end)
return null;
return copy();
}
/**
* {@inheritDoc}
*/
@Override
public Data combined(Data data) {
RangeMaximumData<N> q = null;
if (data instanceof RangeMaximumData) {
q = (RangeMaximumData<N>) data;
this.combined(q);
}
return this;
}
private void combined(RangeMaximumData<N> data) {
if (this.maximum == null && data.maximum == null)
return;
else if (this.maximum != null && data.maximum == null)
return;
else if (this.maximum == null && data.maximum != null)
this.maximum = data.maximum;
else {
/* TODO: This is ugly */
if (this.maximum instanceof BigDecimal || data.maximum instanceof BigDecimal) {
if (((BigDecimal)data.maximum).compareTo(((BigDecimal)this.maximum))==1)
this.maximum = data.maximum;
} else if (this.maximum instanceof BigInteger || data.maximum instanceof BigInteger) {
if (((BigInteger)data.maximum).compareTo(((BigInteger)this.maximum))==1)
this.maximum = data.maximum;
} else if (this.maximum instanceof Long || data.maximum instanceof Long) {
if (((Long)data.maximum).compareTo(((Long)this.maximum))==1)
this.maximum = data.maximum;
} else if (this.maximum instanceof Double || data.maximum instanceof Double) {
if (((Double)data.maximum).compareTo(((Double)this.maximum))==1)
this.maximum = data.maximum;
} else if (this.maximum instanceof Float || data.maximum instanceof Float) {
if (((Float)data.maximum).compareTo(((Float)this.maximum))==1)
this.maximum = data.maximum;
} else {
// Integer
if (((Integer)data.maximum).compareTo(((Integer)this.maximum))==1)
this.maximum = data.maximum;
}
}
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return 31 * (int)(this.start + this.end + this.maximum.hashCode());
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof RangeMaximumData))
return false;
final RangeMaximumData<N> data = (RangeMaximumData<N>) obj;
if (this.start == data.start && this.end == data.end && this.maximum.equals(data.maximum))
return true;
return false;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(super.toString()).append(" ");
builder.append("maximum=").append(maximum);
return builder.toString();
}
}
/**
* Data structure representing minimum in the range.
*/
public static final class RangeMinimumData<N extends Number> extends Data {
public N minimum = null;
public RangeMinimumData(long start, long end) {
super(start, end);
}
public RangeMinimumData(long index, N number) {
super(index);
this.minimum = number;
}
public RangeMinimumData(long start, long end, N number) {
super(start, end);
this.minimum = number;
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
super.clear();
minimum = null;
}
/**
* {@inheritDoc}
*/
@Override
public Data copy() {
return new RangeMinimumData<N>(start, end, minimum);
}
/**
* {@inheritDoc}
*/
@Override
public Data query(long startOfQuery, long endOfQuery) {
if (endOfQuery < this.start || startOfQuery > this.end)
return null;
return copy();
}
/**
* {@inheritDoc}
*/
@Override
public Data combined(Data data) {
RangeMinimumData<N> q = null;
if (data instanceof RangeMinimumData) {
q = (RangeMinimumData<N>) data;
this.combined(q);
}
return this;
}
private void combined(RangeMinimumData<N> data) {
if (this.minimum == null && data.minimum == null)
return;
else if (this.minimum != null && data.minimum == null)
return;
else if (this.minimum == null && data.minimum != null)
this.minimum = data.minimum;
else {
/* TODO: This is ugly */
if (this.minimum instanceof BigDecimal || data.minimum instanceof BigDecimal) {
if (((BigDecimal)data.minimum).compareTo(((BigDecimal)this.minimum))==-1)
this.minimum = data.minimum;
} else if (this.minimum instanceof BigInteger || data.minimum instanceof BigInteger) {
if (((BigInteger)data.minimum).compareTo(((BigInteger)this.minimum))==-1)
this.minimum = data.minimum;
} else if (this.minimum instanceof Long || data.minimum instanceof Long) {
if (((Long)data.minimum).compareTo(((Long)this.minimum))==-1)
this.minimum = data.minimum;
} else if (this.minimum instanceof Double || data.minimum instanceof Double) {
if (((Double)data.minimum).compareTo(((Double)this.minimum))==-1)
this.minimum = data.minimum;
} else if (this.minimum instanceof Float || data.minimum instanceof Float) {
if (((Float)data.minimum).compareTo(((Float)this.minimum))==-1)
this.minimum = data.minimum;
} else {
// Integer
if (((Integer)data.minimum).compareTo(((Integer)this.minimum))==-1)
this.minimum = data.minimum;
}
}
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return 31 * (int)(this.start + this.end + this.minimum.hashCode());
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof RangeMinimumData))
return false;
final RangeMinimumData<N> data = (RangeMinimumData<N>) obj;
if (this.start == data.start && this.end == data.end && this.minimum.equals(data.minimum))
return true;
return false;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(super.toString()).append(" ");
builder.append("minimum=").append(minimum);
return builder.toString();
}
}
/**
* Data structure representing sum of the range.
*/
public static final class RangeSumData<N extends Number> extends Data {
public N sum = null;
public RangeSumData(long start, long end) {
super(start, end);
}
public RangeSumData(long index, N number) {
super(index);
this.sum = number;
}
public RangeSumData(long start, long end, N number) {
super(start, end);
this.sum = number;
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
super.clear();
sum = null;
}
/**
* {@inheritDoc}
*/
@Override
public Data copy() {
return new RangeSumData<N>(start, end, sum);
}
/**
* {@inheritDoc}
*/
@Override
public Data query(long startOfQuery, long endOfQuery) {
if (endOfQuery < this.start || startOfQuery > this.end)
return null;
return copy();
}
/**
* {@inheritDoc}
*/
@Override
public Data combined(Data data) {
RangeSumData<N> q = null;
if (data instanceof RangeSumData) {
q = (RangeSumData<N>) data;
this.combined(q);
}
return this;
}
private void combined(RangeSumData<N> data) {
if (this.sum == null && data.sum == null)
return;
else if (this.sum != null && data.sum == null)
return;
else if (this.sum == null && data.sum != null)
this.sum = data.sum;
else {
/* TODO: This is ugly and how to handle number overflow? */
if (this.sum instanceof BigDecimal || data.sum instanceof BigDecimal) {
BigDecimal result = ((BigDecimal)this.sum).add((BigDecimal)data.sum);
this.sum = (N)result;
} else if (this.sum instanceof BigInteger || data.sum instanceof BigInteger) {
BigInteger result = ((BigInteger)this.sum).add((BigInteger)data.sum);
this.sum = (N)result;
} else if (this.sum instanceof Long || data.sum instanceof Long) {
Long result = (this.sum.longValue() + data.sum.longValue());
this.sum = (N)result;
} else if (this.sum instanceof Double || data.sum instanceof Double) {
Double result = (this.sum.doubleValue() + data.sum.doubleValue());
this.sum = (N)result;
} else if (this.sum instanceof Float || data.sum instanceof Float) {
Float result = (this.sum.floatValue() + data.sum.floatValue());
this.sum = (N)result;
} else {
// Integer
Integer result = (this.sum.intValue() + data.sum.intValue());
this.sum = (N)result;
}
}
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return 31 * (int)(this.start + this.end + this.sum.hashCode());
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof RangeSumData))
return false;
final RangeSumData<N> data = (RangeSumData<N>) obj;
if (this.start == data.start && this.end == data.end && this.sum.equals(data.sum))
return true;
return false;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append(super.toString()).append(" ");
builder.append("sum=").append(sum);
return builder.toString();
}
}
/**
* Data structure representing an interval.
*/
public static final class IntervalData<O extends Object> extends Data {
private Set<O> set = new TreeSet<O>(); // Sorted
/**
* Interval data using O as it's unique identifier
*
* @param object
* Object which defines the interval data
*/
public IntervalData(long index, O object) {
super(index);
this.set.add(object);
}
/**
* Interval data using O as it's unique identifier
*
* @param object
* Object which defines the interval data
*/
public IntervalData(long start, long end, O object) {
super(start, end);
this.set.add(object);
}
/**
* Interval data list which should all be unique
*
* @param set
* of interval data objects
*/
public IntervalData(long start, long end, Set<O> set) {
super(start, end);
this.set = set;
}
/**
* Get the data set in this interval
*
* @return Unmodifiable collection of data objects
*/
public Collection<O> getData() {
return Collections.unmodifiableCollection(this.set);
}
/**
* {@inheritDoc}
*/
@Override
public void clear() {
super.clear();
this.set.clear();
}
/**
* {@inheritDoc}
*/
@Override
public Data copy() {
final Set<O> listCopy = new TreeSet<O>();
listCopy.addAll(set);
return new IntervalData<O>(start, end, listCopy);
}
/**
* {@inheritDoc}
*/
@Override
public Data query(long startOfQuery, long endOfQuery) {
if (endOfQuery < this.start || startOfQuery > this.end)
return null;
return copy();
}
/**
* {@inheritDoc}
*/
@Override
public Data combined(Data data) {
IntervalData<O> q = null;
if (data instanceof IntervalData) {
q = (IntervalData<O>) data;
this.combined(q);
}
return this;
}
/**
* Combined for interval specific data.
*
* @param data
* resulted from combination.
*/
private void combined(IntervalData<O> data) {
if (data.start < this.start)
this.start = data.start;
if (data.end > this.end)
this.end = data.end;
this.set.addAll(data.set);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return 31 * (int)(this.start + this.end + this.set.size());
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object obj) {
if (!(obj instanceof IntervalData))
return false;
final IntervalData<O> data = (IntervalData<O>) obj;
if (this.start == data.start && this.end == data.end) {
if (this.set.size() != data.set.size())
return false;
for (O o : set) {
if (!data.set.contains(o))
return false;
}
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append(super.toString()).append(" ");
builder.append("set=").append(set);
return builder.toString();
}
}
}
/**
* Data structure representing a segment.
*/
protected abstract static class Segment<D extends Data> implements Comparable<Segment<D>> {
protected Segment<D>[] segments = null;
protected int length = 0;
protected int half = 0;
protected long start = 0;
protected long end = 0;
protected D data = null;
protected int minLength = 0;
public Segment(int minLength) {
this.minLength = minLength;
}
/**
* Query for data in range.
*
* @param startOfQuery
* of the range to query for.
* @param endOfQuery
* of range to query for.
* @return Data in the range.
*/
public abstract D query(long startOfQuery, long endOfQuery);
protected boolean hasChildren() {
return (segments != null);
}
protected Segment<D> getLeftChild() {
return segments[0];
}
protected Segment<D> getRightChild() {
return segments[1];
}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append(start).append("->");
builder.append(end).append(" ");
builder.append("Length=").append(length).append(" ");
builder.append("Data={").append(data).append("}");
return builder.toString();
}
/**
* {@inheritDoc}
*/
@Override
public int compareTo(Segment<D> p) {
if (this.end < p.end)
return -1;
if (p.end < this.end)
return 1;
return 0;
}
}
protected static class SegmentTreePrinter {
public static <D extends SegmentTree.Data> String getString(SegmentTree<D> tree) {
if (tree.root == null)
return "Tree has no nodes.";
return getString(tree.root, "", true);
}
private static <D extends SegmentTree.Data> String getString(Segment<D> segment, String prefix, boolean isTail) {
final StringBuilder builder = new StringBuilder();
builder.append(prefix + (isTail ? "└── " : "├── ") + segment.toString() + "\n");
final List<Segment<D>> children = new ArrayList<Segment<D>>();
if (segment.segments != null) {
for (Segment<D> c : segment.segments)
children.add(c);
}
for (int i = 0; i < children.size() - 1; i++)
builder.append(getString(children.get(i), prefix + (isTail ? " " : "│ "), false));
if (children.size() > 1)
builder.append(getString(children.get(children.size() - 1), prefix + (isTail ? " " : "│ "), true));
return builder.toString();
}
}
/**
* Flat segment tree is a variant of segment tree that is designed to store
* a collection of non-overlapping segments. This structure is efficient
* when you need to store values associated with 1 dimensional segments that
* never overlap with each other. The end points of stored segments are
* inclusive, that is, when a segment spans from 2 to 6, an arbitrary point
* x within that segment can take a value of 2 <= x <= 6.
*/
public static final class FlatSegmentTree<D extends Data> extends SegmentTree<D> {
public FlatSegmentTree(List<D> data) {
this(data, 1);
}
public FlatSegmentTree(List<D> data, int minLength) {
if (data.size() <= 0)
throw new InvalidParameterException("Segments list is empty.");
Collections.sort(data); // Make sure they are sorted
// Make sure they don't overlap
if (data.size() >= 2) {
for (int i = 0; i < (data.size() - 2); i++) {
Data s1 = data.get(i);
Data s2 = data.get(i + 1);
if (s1.end > s2.start)
throw new InvalidParameterException("Segments are overlapping.");
}
}
// Check for gaps
final List<NonOverlappingSegment<D>> segments = new ArrayList<NonOverlappingSegment<D>>();
for (int i = 0; i < data.size(); i++) {
if (i < data.size() - 1) {
final Data d1 = data.get(i);
final NonOverlappingSegment<D> s1 = new NonOverlappingSegment<D>(minLength, d1.start, d1.end, (D) d1);
segments.add(s1);
final Data d2 = data.get(i + 1);
if (d2.start - d1.end > 1) {
final Data d3 = d1.copy();
d3.clear();
d3.start = d1.end + 1;
d3.end = d2.start - 1;
final NonOverlappingSegment<D> s3 = new NonOverlappingSegment<D>(minLength, d3.start, d3.end, (D) d3);
segments.add(s3);
}
} else {
final Data d1 = data.get(i);
final NonOverlappingSegment<D> s1 = new NonOverlappingSegment<D>(minLength, d1.start, d1.end, (D) d1);
segments.add(s1);
}
}
final long start = segments.get(0).start;
final long end = segments.get(segments.size() - 1).end;
final int length = (int) (end - start) + 1;
root = NonOverlappingSegment.createFromList(minLength, segments, start, length);
}
/**
* {@inheritDoc}
*/
@Override
public D query(long index) {
return this.query(index, index);
}
/**
* {@inheritDoc}
*/
@Override
public D query(long startOfQuery, long endOfQuery) {
if (root == null)
return null;
long s = startOfQuery;
long e = endOfQuery;
if (s < root.start)
s = root.start;
if (e > root.end)
e = root.end;
return root.query(s, e);
}
/**
* Data structure representing a non-overlapping segment.
*/
protected static final class NonOverlappingSegment<D extends Data> extends Segment<D> {