-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPBDS java (upto N)
122 lines (102 loc) · 2.14 KB
/
PBDS java (upto N)
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
class PBDS{
private int N; // tot number of Nodes
private int[] bit; // Binary Index Tree
private int tot; // Keep track of number of elements
private TreeSet<Integer> tree;
private boolean duplicate; // duplicates are Allowed or Not
PBDS(boolean duplicate , int n){
this.duplicate = duplicate;
tree = new TreeSet<>();
this.N = (int)(n + 1);
bit = new int[N];
this.tot = 0;
}
// update BIT
private void update(int ind , int val ) {
for( ; ind<N ;ind += (ind & (-ind))) {
bit[ind] += val;
}
}
// PREFIX SUM for given index
private int val(int ind) {
int tot = 0;
while(ind > 0) {
tot += bit[ind];
ind -= (ind & (-ind));
}
return tot;
}
void add(int ele) {
Integer ind = ele;
if(ind == null) return;
if(!duplicate && count(ind) > 0) return;
update(ind , 1);
tree.add(ele);
tot++;
}
boolean contains(int ele) {
Integer ind = ele;
if(ind == null) return false;
return count(ind) > 0;
}
private int count(int ele) {
return val(ele) - val(ele - 1);
}
boolean remove(int ele) {
Integer ind = ele;
if(ind == null) return false;
if(count(ind) == 0 ) return false;
if(count(ind) == 1) tree.remove(ele);
update(ind , -1);
tot--;
return true;
}
int size() {
return tot;
}
Integer eleAtIndex(int index) {
if(index > tot || index < 1) return null;
int l = 1 , r = N-1;
while(l<=r) {
int m = (l+r)/2;
if(val(m) < index) l = m+1;
else r = m-1;
}
return l;
}
int count_ceil(int ele) {
int l = 1 , r = N-1;
int ind = ele-1;
int count = val(ind);
return tot - count;
}
Integer ceil(int ele) {
return tree.ceiling(ele);
}
int count_floor(int ele) {
int ind = ele;
int count = val(ind);
return count;
}
Integer floor(int ele) {
return tree.floor(ele);
}
void clearAll() {
while(!tree.isEmpty()) {
int first = tree.first();
while(count(first) > 0) this.remove(first);
tree.remove(first);
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
for(int i = 1 ; i<N ; i++) {
int c = count(i);
int ele = i;
while(c -- >0) {
sb.append(ele +",");
}
}
return String.valueOf(sb);
}
}