Problems
Give an array consists N integers and Q queries, with two types :
- ? k -> print the kth element in this array.
- ! k -> remove the kth element in this array.
a[i] <= 1e9 N, Q <= 2e5
This problem likes "List Removal" problems on Cses (here)
Naive Approach
Using brute-force, query 1 will be processed in O(1), query 2 will be processed in O(n).
Code:
void Query_1(int k) {
cout<<a[k]<<" ";
}
void Query_2(int k) {
for (int i = k; i < n; i++) a[i] = a[i + 1];
n--;
}
O(nlog(n)log(n)) / O(nlogn) using IT, BIT
Because using IT(Segment Tree) and BIT is the same, so now I talking about IT.
Firstly, we will have an array B, B[i] = 1 if ith element not deleted yet, B[i] = 0 otherwise. We will build a Segment Tree whose each node has 1 value, it is the sum B[i] in [L, R].
Now, we can find the kth element in the array easily by binary search. Code:
int Find(int k) {
int l = 1, r = n, mid, res;
while (l <= r) {
mid = (l + r) >> 1;
if (GetSum(1, mid) >= k) {
res = mid;
r = mid - 1;
}
else l = mid + 1;
}
return res;
}
We can optimize the complexity from O(nlog(n)^2) to O(nlog(n)) using "Walk on segment tree" technique.
O(nlogn), using ordered_set ------------------
This problem can solve very easily by ordered_set: https://www.geeksforgeeks.org/ordered-set-gnu-c-pbds/
Using Trie, O(n) complexity
[](https://www.geeksforgeeks.org/trie-insert-and-search/) This is for people who don't know Trie.
The main idea is inserting all index in array into Trie. Firstly, we will converse all index to string, and all string has the same length (we will insert "0" before some strings). Now the problem is find the Kth string (lexicographically) smallest in Trie.
We will build a Trie, each node like :
struct Node {
Node* child[10];
int cnt, val;
Node() {
for (int i = 0; i < 10; i++) child[i] = NULL;
cnt = val = 0;
}
};
- cnt : numbers of string pass this node
- val : if this Node is the end of a string (index), val = a[index].
Okay, now we will find the way to reach the Kth smallest string (lexicographically).
Consider we add some strings into Trie: "00123" "00124" "00234" "00245"
And K = 4
We will have Trie like :