We are given a string s (length up to 2e5) and m queries (m up to 40000). For each query, we need to delete the K-th occurrence of character x from the current string. After all queries, print the resulting string. We need to process these deletions efficiently.
Constraints: The string length is up to 200k, m up to 40k. So we need to perform up to 40k deletions. A naive approach would be to delete from the string which could be O(n) per deletion, leading to O(m n) worst-case 8e9, not acceptable. We need something like O((n+m) log n) or similar.
We need to support operations: find the position of the K-th occurrence of a specific character in the current string, then delete that character at that position. The string is dynamic (deletions only). The order of characters matters.
We can think of maintaining a Fenwick tree or segment tree over the current string to track which indices are still present. Initially we have indices 1..n. Each deletion removes one character. We need to find the actual index in the original string that corresponds to the K-th occurrence of x in the current remaining string.
One approach: For each character (26 letters), maintain a data structure (e.g., BIT) over the positions where that character appears in the original string. As we delete characters, we need to remove them from the BIT for that character, and also from a global BIT that tracks all positions (to map from rank to original index). Alternatively, we can avoid the global BIT by using the character-specific BITs to find the K-th occurrence of x among remaining characters of that type: the BIT for character x stores 1 at each original position where the character is x, but only for those not yet deleted. Then the K-th occurrence of x corresponds to finding the smallest index such that prefix sum = K. This works if we only consider positions of that character. But we need to ensure that the deletions of other characters don't affect the ordering of occurrences of x? Actually the ordering of occurrences of x is determined by their positions in the string. If we delete other characters, the positions of x don't change; the K-th occurrence of x in the current string is still the K-th x in order of increasing original index among the remaining x's. Because deletions of other characters don't affect the relative order of x's. So indeed we can maintain for each character a BIT over its original positions. We can mark deletions by setting that position to 0. Then to get the K-th occurrence we need to find the smallest position with prefix sum = K. That's a standard operation with BIT (by binary lifting). This BIT size = n (max 2e5), which is fine. For each query, we need to delete the K-th occurrence of x, i.e., find its original index, then update BIT for x (set to 0). Also we might need to update something else? Actually the problem only asks for final string after all deletions. We could at the end reconstruct the string by iterating over original indices and including characters that haven't been deleted. So we need to know which positions are deleted. So in addition to the per-character BIT updates, we need to mark a global array deleted[pos] = true. So after processing all queries, we can output s[i] for i from 1 to n if not deleted.
But we also need to consider that a character might be deleted from multiple letters? No, each deletion is for a specific character x. So we only update BIT for that character. The global deleted array is updated accordingly.
Complexities: For each query, we need to find the K-th occurrence in BIT of x. BIT find by order (select) can be done in O(log n) (by binary search on BIT). Then we set that position to 0, O(log n). So total O((n + m) log n) time. n up to 2e5, m up to 4e4, that's fine.
But careful: The BIT for each character: we have 26 letters. We could create 26 BITs each of size n. That's 26 * 2e5 = 5.2e6, which is okay in memory (5.2 million integers, about 20 MB if 4 bytes each). But each BIT typically uses 1-indexed array of size n+1. So memory ~ 26 * (2e5+1) * 4 bytes = ~21 MB, acceptable. Alternatively, we could store vectors of positions for each character and use a Fenwick tree over each vector (since number of positions for each character varies). However, since we need to handle deletions efficiently, we could maintain for each character a BIT over its positions in sorted order. For each character, we have a list of indices where it occurs originally. The K-th occurrence corresponds to the K-th index in the list (if we skip deleted ones). We could maintain a BIT over the list (size = count of that character). For each deletion, we need to remove the element at position K in the list (the K-th remaining). But careful: the list is static (original positions) and the order is by increasing index. We can use a BIT with size = number of occurrences of that character. Initially, all are present, so BIT[i] = 1. When we need to delete the K-th remaining occurrence, we find the smallest index i in the BIT such that prefix sum = K, then the original position = pos_list[i]. Then we set BIT[i] = 0. That works and might be more memory efficient (total elements across all BITs = n). However, we need to map back from original position to the character's list index? Actually we only need to know the original position to mark deleted[pos] = true. In this method, we can directly get original position from the list. This approach uses only O(n) total memory, and per character BIT size equals its count. But we need to allocate BIT per character. Implementation wise, we could store for each character a vector of positions, and a BIT (Fenwick tree) as a separate vector of ints with size = length of that vector. For each query, we locate the index in that vector using BIT select, then delete it (set to 0) and also mark deleted[pos] = true. That's efficient. The BIT select operation in a BIT sized by count works similarly. Also we need to ensure that we can find the K-th remaining occurrence: Since we maintain the BIT over the list, the order corresponds to occurrence order. The BIT's prefix sum gives number of remaining occurrences among first i items. So we can binary search for smallest i such that prefix sum = K.
This approach is slightly more complex but not much. However, the simpler approach of 26 BITs over the full string might be easier to code: For each character c, we create BIT of size n, initially set 1 at positions where s[i]==c, else 0. Then to find K-th occurrence of c: we need to find smallest index p such that sum_{1..p} BIT_c = K. That's standard. Then we set BIT_c[p] = 0; also set global deleted[p] = true. However, we need to note that after deletions, the BIT_c reflects only the remaining positions of c. That's fine.
But there is a nuance: when we delete a character at position p, it also affects the BITs for other characters? No, because BITs are per character, only the BIT for that character should be updated (set to 0). Since that position originally had character c, it's only set to 1 in BIT_c; other BITs have 0 there. So we don't need to update other BITs. However, we need to ensure that future queries for other characters don't consider that position because it's deleted; but as other BITs have 0 at that position originally, they wouldn't count it anyway. So it's fine.
Thus, per-character full BIT works straightforwardly.
But the memory of 26 BITs of size n might be okay but we need to store them as array of ints? Actually BIT needs an array of size n+1 (or n). 26 * (200001) ≈ 5.2e6 ints. In Python, memory might be high because ints are objects (28 bytes each) leading to huge memory (over 100 MB). In C++ it's fine, but this problem statement likely expects C++? However, we are given an environment (maybe we need to implement in any language). The constraints: string length 2e5, m 40000. In Python, using 26 lists of size n+1 of integers might be borderline but possibly okay? Let's approximate: each integer in Python is an object ~28 bytes. 5.2e6 * 28 = ~145 MB, plus overhead, maybe > 200 MB. That's too high for typical limits (256 MB perhaps still okay? But Python's overhead is high, and list of ints actually stores references to Python int objects; each int is separate object. Even using array('i') from array module or using list of ints but Python ints are arbitrary precision but small ints are cached? Actually small ints from -5 to 256 are cached, but we are storing 0/1, so they will be small ints that are reused, but each list slot holds a reference to the same int object? No, list stores references; the int objects are reused because small ints are interned, so the memory for each list entry is just the pointer (8 bytes). So each list slot is 8 bytes, plus the list overhead. So 5.2e6 * 8 = 41.6 MB. Plus list overhead ~ 5.2e6 * ? Actually list overhead: a Python list has an array of pointers; each pointer is 8 bytes. So 5.2e6 * 8 = 41.6 MB. That's acceptable. But we have 26 lists, each with length n+1 = 200001, so 26 * 200001 = 5,200,026 slots. 5.2 million * 8 = 41.6 MB. That's okay. However, we also need to store the BIT arrays as Python lists of ints. But each list itself has overhead. That should be within 256 MB. But we must also store the original string, global deleted flags, etc. So it's feasible.
But we need to implement BIT operations efficiently in Python. For each query, we do find K-th occurrence using BIT binary lifting. That's O(log n). With m up to 40000, that's fine.
However, there is a catch: For BIT select, we need to find smallest index with given prefix sum. BIT typical implementation uses a method like:
def find_kth(bit, k):
idx = 0
bit_mask = highest_power_of_two_leq(n)
while bit_mask:
next_idx = idx + bit_mask
if next_idx <= n and bit[next_idx] < k:
k -= bit[next_idx]
idx = next_idx
bit_mask >>= 1
return idx + 1
This works if bit stores cumulative frequencies in Fenwick manner. But we need to ensure that the BIT contains only 0/1 values. That's fine.
So we can do:
-
n = len(s)
-
For each character ch in 'a'..'z', create BIT array of size n+1 initialized to 0.
-
Iterate over s (1-indexed), for each position i, char c, do bit_add(bit_of(c), i, 1)
-
Also store s as list for later output.
-
Create deleted = [False] * (n+1) (1-indexed)
-
For each query (K, x):
- Let bit = BIT for char x.
- p = find_kth(bit, K) # returns index of the K-th 1
- Then bit_add(bit, p, -1) # delete it (set to 0)
- deleted[p] = True
-
After all queries, build result string: for i in 1..n, if not deleted[i]: result.append(s[i-1]) (since s is 0-indexed originally)
-
Print result.
But we must be careful: The input string can be large; using Python loops for building BIT may be okay.
Alternative approach: Use BIT per character over compressed positions (list of indices). That would use less memory and maybe faster? But the per-character full BIT is simpler.
Let's test with sample:
s = "abcdbcaab", n=9
Positions:
1 a
2 b
3 c
4 d
5 b
6 c
7 a
8 a
9 b
We'll create BIT for 'a': positions 1,7,8 => after init: BIT has 1 at these positions.
Query: 2 a: find 2nd occurrence of a => position 7? Actually 1st a at pos1, 2nd at pos7. Delete pos7.
After that, BIT a: positions 1,8 remain.
Then 1 c: positions of c: 3,6. 1st c at pos3 -> delete pos3.
1 d: positions of d: 4 -> delete pos4.
3 b: positions of b: 2,5,9. After deletions? No deletions of b yet. 3rd b at pos9 -> delete pos9.
2 a: now remaining a: positions 1,8. 2nd a is at pos8? Actually 1st at pos1, 2nd at pos8 -> delete pos8.
Remaining characters: a at pos1, b at pos2, b at pos5? Wait b at pos5 still? Did we delete b at pos9 only. So remaining: pos1 a, pos2 b, pos5 b, also any c? We deleted c at pos3 and also c at pos6? Actually we only deleted first c (pos3). c at pos6 remains? No, only one query for c (1 c) so only pos3 c deleted, pos6 c still there. d deleted (pos4). Also we deleted a at pos7 and pos8, so remaining a at pos1. b: pos2, pos5 remain. c: pos6 remains. So remaining positions: 1 a,2 b,5 b,6 c. That's "abbc"? Actually order: pos1 a, pos2 b, pos5 b, pos6 c -> "abbc". But sample output is "abbc". Good.
So algorithm works.
Potential issues: The BIT find_kth assumes that there are at least K ones. Since it's guaranteed that operation is correct, we are safe.
Now time complexity: initialization O(26 + n log n) if we add each position to BIT: each addition is O(log n). For n=2e5, that's about 2e5 * log2(2e5) ~ 2e5 * 18 = 3.6e6 operations, fine. Queries: each query does find_kth (O(log n)) and update (O(log n)) => 8e4 * log n ~ 8e4 * 18 = 1.44e6. So total ~5 million operations, fine in Python.
Implementation details:
- Read input: first line contains string s and integer m? Actually sample input: first line "abcdbcaab 5"? In problem statement: "The first line contains the string s followed by an integer m." So there might be space separated: s and m on same line. Then m lines follow each with K and x. So we need to parse first line: read whole line, split, first part is s, second part is m. Could also be two lines? According to sample, it's on one line. So we read line, split. If length>1, then s = parts[0], m = int(parts[1]). But if it's two lines, maybe they split; we can robustly handle: first token is s, then maybe m on same line or next. Better: read entire input as tokens using sys.stdin.read().split(). Then first token is s, second token is m, then 2*m tokens for queries (each K then x). That is simpler.
So: data = sys.stdin.read().split()
s = data[0]
m = int(data[1])
Then queries: for i in range(m):
K = int(data[2+2i])
x = data[2+2i+1] # it's a string of length 1 char.
But careful: x may be a character like 'a'. That's fine.
-
n = len(s)
-
Preprocess: For each char, create BIT list of length n+1 zeros. Since we have 26 lowercase letters, we can map char to index 0-25. Create a list of 26 BIT arrays: bits = [[0]*(n+1) for _ in range(26)]
-
Initialize: for idx, ch in enumerate(s, start=1): c_index = ord(ch)-97; then call add(bits[c_index], idx, 1) (Fenwick add function)
Fenwick functions:
def fenwick_add(bit, idx, delta):
while idx <= n:
bit[idx] += delta
idx += idx & -idx
def fenwick_sum(bit, idx):
s=0
while idx>0:
s+=bit[idx]
idx -= idx & -idx
return s
def fenwick_find_kth(bit, k): # 1-indexed k, returns smallest idx such that prefix sum >= k? Actually we need exactly k.
# Assumes k >=1 and <= total sum.
idx = 0
bit_mask = 1 << (n.bit_length()) # highest power of two >= n?
while bit_mask:
next_idx = idx + bit_mask
if next_idx <= n and bit[next_idx] < k:
k -= bit[next_idx]
idx = next_idx
bit_mask >>= 1
return idx + 1
But we need to compute the largest power of two <= n. We can compute: bit_mask = 1 << (n.bit_length() - 1) # highest power of two <= n.
Or compute: bit_mask = 1
while bit_mask <= n: bit_mask <<= 1; then bit_mask >>= 1.
But in Python, to avoid recomputation, we can compute size = n and then bit_mask = 1 << (size.bit_length() - 1).
But careful: Fenwick find_kth works when BIT stores cumulative frequencies. The typical code:
pos = 0
bit_mask = highestPowerOfTwo(n)
while bit_mask:
next_pos = pos + bit_mask
if next_pos <= n and tree[next_pos] < k:
k -= tree[next_pos]
pos = next_pos
bit_mask >>= 1
return pos + 1
This yields the smallest index such that prefix sum = K (if tree is Fenwick). Works when all values are non-negative. Since we have only 0/1, it's fine.
But we need to ensure that total sum in BIT for char x is at least K. That's guaranteed.
So for each query: c_index = ord(x)-97; bit = bits[c_index]; pos = fenwick_find_kth(bit, K); then fenwick_add(bit, pos, -1); deleted[pos] = True.
At the end, output: print(''.join(s[i] for i in range(n) if not deleted[i+1]))
Now test with sample.
But need to consider: The BIT per character is of size n. However, find_kth uses n as the size. Since BIT array may have size n+1, but we treat indices from 1 to n. The binary mask should be based on n. That's okay.
Potential pitfalls:
-
The BIT_find_kth function expects that the BIT stores cumulative sums in Fenwick tree format. It works as long as we use the standard Fenwick tree updates. We'll implement accordingly.
-
The initial BIT building: we add 1 for each position. This is O(n log n). Could we do a more efficient initialization by building BIT from an array of frequencies? In Fenwick, we could initially set bits[i] = number of occurrences at i? But that's not straightforward. Since n=2e5, O(n log n) is fine.
-
Memory: bits = list of 26 lists each of length n+1. In Python, a list of 26 lists, each list of n+1 integers. n+1 ~ 200001. So total 5.2 million integers. That's okay.
-
However, we also have deleted list of size n+1 booleans. In Python, bool is subclass of int, but list of bool also stores references to True/False objects? Actually bool objects are singletons, but list of bools still stores pointers (8 bytes each). So similar memory. So total ~ additional 1.6 MB for deleted? Actually n+1 ~ 200001, *8 = 1.6 MB. So total < 50 MB. That's fine.
But careful: Using Python's list of lists for BIT, we must ensure that we don't accidentally create shallow copies. We'll do: bits = [[0]*(n+1) for _ in range(26)].
Now test with sample.
We'll code.
Edge Cases:
-
Deleting all characters: final string empty? Problem says "string is never empty" after each operation? Actually note: "It is guaranteed that the operations are correct, that is , the letter to be deleted always exists and the string is never empty." So after all deletions, string might be empty? Possibly but they guarantee during operations it's never empty, but after all deletions it might be empty? Could be. So we need to handle empty output. That's fine.
-
K can be up to the number of occurrences of x at that time, but we have guarantee.
-
The string length initially up to 2e5, m up to 4e4. So deletions up to 4e4, so final string length at least n - m.
Now complexities are fine.
But we need to consider that the BIT find_kth uses the global n (the original length). However, after some deletions, the BIT for character x may have zeros at many positions, but the BIT tree still stores cumulative sums up to n. The find_kth algorithm still works because it only uses the tree entries. The tree entries reflect the current state. So it's correct.
Now we should test with some random cases to ensure correctness.
Alternatively, we can avoid BIT per character and use segment tree with 26? But BIT is simpler.
Potential issues: The BIT find_kth implementation might be off by one. We'll test.
Let's write a simple test:
Suppose n=5, positions of 'a': at indices 2 and 5. BIT initially: add at 2 and 5.
Fenwick tree representation: after adding 1 at positions, we can compute prefix sums. To find 1st occurrence (k=1), expected idx=2. Let's simulate: n=5, highest power of two <=5 is 4. bit_mask=4, idx=0, next=4, if next<=5 and tree[4] < 1? tree[4] = sum of range? We need to know tree values. In Fenwick, tree[i] stores sum of range (i - lowbit(i)+1, i]. So we need to compute tree after adding at 2 and 5. Let's manually:
- Initially all zeros.
- Add at 2: update indexes: 2,4. tree[2]=1, tree[4]=1.
- Add at 5: update 5,6? but n=5, so 5 only. tree[5]=1.
So tree array: index: 1:0,2:1,3:0,4:1,5:1.
Now find k=1:
bit_mask=4 (since 1<<(5.bit_length()-1) = 1<<(3-1?) Wait 5.bit_length()=3, so 1<<2=4). idx=0.
next=0+4=4, tree[4]=1, condition tree[4] < k? 1<1 false, so do nothing. bit_mask>>=1 =>2.
next=0+2=2, tree[2]=1, condition 1<1 false. bit_mask>>=1=>1.
next=0+1=1, tree[1]=0, condition 0<1 true, so k -=0 (k remains 1), idx=1. bit_mask>>=1=>0.
Loop ends. Return idx+1=2. Good.
Now k=2: expected idx=5.
Initialize bit_mask=4, idx=0, k=2.
next=4, tree[4]=1, 1<2 true, so k-=1 => k=1, idx=4. bit_mask>>=1 =>2.
next=4+2=6 > n? 6>5, so skip (condition next<=n fails). bit_mask>>=1=>1.
next=4+1=5, tree[5]=1, 1<1 false, so idx stays 4. bit_mask>>=1=>0.
Return idx+1=5. Good.
So find_kth works.
Edge case: if the BIT tree has cumulative sum at the exact point, it returns correct index.
Now confirm for other characters: For characters not present, we never query because it's guaranteed that K-th occurrence exists.
Now about input reading: In the sample, the first line is "abcdbcaab 5". So we can read as described.
Potential pitfalls: The string may contain spaces? No, only lowercase letters. So splitting works.
Now we should also consider that m can be up to 40000, but the input size is small.
Now coding.
But we need to be careful about using sys.stdin.read().split() will load all tokens into memory, which is fine.
Now I'll produce final solution.
However, there might be a more efficient solution using order statistic tree or something, but BIT is enough.
But let's double-check the complexity for initial BIT building: For each position i (1..n), we add 1 to the BIT of that character. That's 26 separate BITs, but we only update one BIT per position. So total O(n log n).
Now the memory consumption: 26*(n+1) ints. In Python, as said, list of ints uses 8 bytes per pointer, plus the int objects themselves are shared for small ints 0 and 1, but there are only two distinct int objects (0 and 1). However, each list entry is a reference to the same int object? Actually when we create [0]*(n+1), it creates a list of n+1 references to the same 0 object. That's fine because ints are immutable. When we later do bit[idx] += delta, that will assign a new integer to bit[idx] (since ints are immutable, we cannot change the object). But the list entry is replaced with a new int object (the updated sum). But during the updates, we will be assigning various integer values. However, the initial list has all zeros references to the same 0 object. After updates, some entries become positive numbers. But that's okay. The memory for the int objects themselves will be allocated as needed. However, each unique integer value may be reused? Python caches small integers from -5 to 256, so all sums in BIT (which are up to n) may exceed that range but typical values for a BIT entry can be up to the number of elements in that range, which could be up to n. For large n, sums can be large (up to 2e5). But Python's small integer cache only covers a small range; larger ints are new objects. So many BIT entries will hold large integers, each taking memory for the int object (28 bytes). That could be a problem: In per-character BIT, we have many entries that hold cumulative sums, not just 0/1. Since BIT stores sums of ranges, many entries will have values > 1. For example, for a character that appears many times, BIT entries will hold counts. That means that the list entries no longer just reference small ints, but each entry holds a Python int object that may be larger. In typical Fenwick tree, each index i stores sum of a range. For a character that appears at many positions, some BIT entries could hold values up to the number of occurrences of that character in that range. So each BIT entry is a Python integer object, and they are distinct (except when same value coincidentally, but Python might not reuse). So memory usage could be significant: each of the 5.2 million entries will hold an integer (0 to maybe up to 2e5). That means we have 5.2 million Python integer objects, each around 28 bytes => ~145 MB. That's quite high. The earlier assumption that entries are just pointers to shared small ints is false because many entries will be replaced with arbitrary integers during updates. Actually we build the BIT by starting from zeros, then for each occurrence we call add. Each add updates O(log n) entries, each setting the value to a new integer (old value + 1). So many entries become positive numbers. After building all BITs, almost every entry in BIT of each character will have been updated? Let's think: For each character, its BIT is initially all zeros. Then we add 1 at each position where that character occurs. For each such position, we update O(log n) entries in that BIT. So the total number of updates across all BITs is O(n log n) (since each position updates exactly one BIT). So the total number of entries that become non-zero is at most O(n log n) across all BITs? Actually each update touches about log n indices, and across all characters, we have total updates = n * log n (since each position updates its character's BIT). However, each BIT entry can be updated multiple times. But after all updates, many entries might still be zero if no update touched them. For a character that appears rarely, many BIT entries remain zero (and they reference the same 0 object). For a character that appears often, many entries become positive. In worst case, all characters appear equally? Actually maximum total number of updated entries across all BITs is bounded by total number of updates times 1? Wait each update modifies a specific index in the BIT. The set of indices that get modified across all updates is the union of indices that are touched. Since each BIT is separate, the total number of distinct indices that become non-zero across all BITs is at most the total number of updates, but each update sets an index to a new value, but if an index is updated multiple times, it will hold the final sum. So the total number of BIT entries that become non-zero is at most the number of indices that ever receive an update. For each character, the number of indices updated in its BIT is at most (number of occurrences of that character) * log n. But many of these indices may overlap. In the worst case, if a character appears at every position, then during initialization we add 1 at each position; this updates, for each position i, the indices i, i+lowbit(i), etc. Over n positions, the set of indices that get updated is essentially all indices from 1 to n (because the Fenwick tree structure ensures that for each index j, there exists some i such that updating i will affect j). Actually for a BIT, if we add 1 at every index i from 1 to n, then every BIT entry j will receive a number of updates equal to the number of i such that j is in the update path of i. But ultimately, all BIT entries j will become positive because at least when we add at i=j, we update j directly. So if a character appears at all positions (n occurrences), then after building, every entry in that BIT will be >0. So for that character, all n+1 entries (except maybe index 0 not used) become non-zero. That's 2e5 int objects. For 26 characters, if all appear at many positions, the total number of non-zero entries could approach 26 * n = 5.2 million, each holding a Python int. That could be memory heavy (~150 MB). But maybe it's still okay within memory limit? Usually Python memory limit is 256 MB, so 150 MB might be okay, but there is also overhead for list objects themselves, plus other data. However, we also have overhead for the list of lists (the outer list and each inner list). The inner list itself is an array of PyObject pointers, each 8 bytes. So the pointers array takes 5.2 million * 8 = ~41.6 MB. The integer objects themselves take additional memory, but many of them will be small integers (up to maybe 2e5). Python int objects are 28 bytes on 64-bit (depending on version; typically 28 bytes for small ints? Actually sys.getsizeof(0) returns 24? Let's recall: Python 3.8 on 64-bit: int object overhead is 28 bytes? In typical CPython 3.10, an int object is 28 bytes. So 5.2 million * 28 = ~145.6 MB. Combined with pointer array ~41.6 MB gives ~187 MB. Plus other structures: string, deleted list, etc., maybe 200 MB. This might be borderline but could pass if memory limit is 256 MB. However, there is also overhead for the list objects: each list has overhead ~56 bytes, plus the array of pointers. So total maybe around 200-210 MB. Might be okay but there's risk of memory limit exceeded in some judges.
Thus, the per-character BIT approach might be memory-hungry in Python. To be safe, we could use the compressed BIT approach: For each character, store a list of positions and a BIT over that list. That way the total number of elements across all BITs is exactly n (the total number of characters). And each BIT entry is also an integer (0/1) but we need to store the BIT array of length equal to the count of that character + 1. So total size of BIT arrays = sum over characters (cnt[c] + 1) ≈ n + 26. That's about 2e5 integers, which is tiny. However, we also need to store the positions list for each character (the same n positions). So total memory for positions: n integers (the original indices). And BIT arrays: n integers. So total ~2n integers = 400k integers, far less. Also we need to maintain BIT updates for deletions (set to 0). So this approach is much more memory efficient.
Let's evaluate: For each character c, we have a vector pos[c] = sorted list of indices (1-based) where c occurs. We'll also have a BIT (Fenwick) bit_c of size len(pos[c]) initially filled with 1s. When we need to delete the K-th occurrence of c, we find the index i in bit_c such that prefix sum = K (i is the index in the pos list). Then we get original position p = pos[c][i-1] (if 0-indexed). Then we set bit_c[i] to 0 (update with -1). Also mark deleted[p] = True.
This method uses only O(n) memory total. And operations: find K-th in BIT of size count_c (which can be up to n), but overall still O(log count_c) per query, which is O(log n). And initialization: we need to build BIT for each character: we could initialize BIT by setting each entry to 1 via prefix sums or by building from array. Since counts per character sum to n, total initialization O(n). So it's efficient and memory-friendly.
Thus, I'll adopt the compressed BIT approach.
Implementation details:
-
Read input.
-
s: string.
-
n = len(s)
-
Create an array of 26 lists: positions = [[] for _ in range(26)]
-
For i, ch in enumerate(s, start=1): idx = ord(ch)-97; positions[idx].append(i)
-
For each character c, let sz = len(positions[c]).
Create BIT array bit_c of length sz+1 (1-indexed). Initially, we want bit_c[i] = 1 for each i. The easiest is to create list bit = [0]*(sz+1), then for i from 1 to sz: call add(i, 1). That would be O(sz log sz) per character, total O(n log n). But we can also build BIT in O(sz) by setting bit[i] = 1 initially and then building cumulative structure: for i in range(1, sz+1): j = i + (i & -i); if j <= sz: bit[j] += bit[i]. However, we need the BIT to function correctly; that's a standard BIT building from an initial array. We can create an array arr of 1's of length sz+1 (with arr[0]=0) and then build BIT. But that requires extra array. Simpler: just do add for each element; total O(n log n) is fine (n=2e5, log n ~18, so 3.6e6 operations, okay). But we might also need to support dynamic deletions: each deletion uses add with -1. That's fine.
So for each character list, we'll create BIT as a list of zeros of size sz+1. Then for i in range(1, sz+1): we can do add(bit, i, 1). That's O(sz log sz) total ~ n log n. Acceptable.
Alternatively, we can do:
bit = [0]*(sz+1)
for i in range(1, sz+1):
bit[i] = 1
j = i + (i & -i)
if j <= sz:
bit[j] += bit[i]
But careful: This sets bit[i] to 1 and then propagates to its parent. However, the standard build from initial array is:
bit = [0]*(sz+1)
for i in range(1, sz+1):
bit[i] = arr[i] # arr[i] initial frequency
for i in range(1, sz+1):
j = i + (i & -i)
if j <= sz:
bit[j] += bit[i]
If we set arr[i]=1, we can do that. But we must ensure we don't double count. Let's just use add for simplicity.
Now we also need a way to map from character x to its BIT and positions list.
We'll store arrays:
- pos = [list() for _ in range(26)]
- bit = [None]*26 # each will be a Fenwick list
After building pos, we initialize bits for each non-empty list.
Fenwick functions:
def fenwick_add(bit, idx, delta):
while idx < len(bit):
bit[idx] += delta
idx += idx & -idx
def fenwick_sum(bit, idx):
s = 0
while idx>0:
s += bit[idx]
idx -= idx & -idx
return s
def fenwick_find_kth(bit, k):
# bit is 1-indexed, we assume sum(bit) >= k
idx = 0
bit_mask = 1 << ( (len(bit)-1).bit_length() - 1 ) # highest power of two <= size (len(bit)-1 is n)
while bit_mask:
next_idx = idx + bit_mask
if next_idx < len(bit) and bit[next_idx] < k:
k -= bit[next_idx]
idx = next_idx
bit_mask >>= 1
return idx + 1
Note: len(bit) is sz+1, so max index = sz. So we can compute highest power of two <= sz.
We could also compute it once per character per query but we can compute inside function each time; it's O(1) overhead.
Now process queries:
deleted = [False]*(n+1) # 1-indexed
For each query (K, x):
c_idx = ord(x)-97
bit_c = bits[c_idx]
pos_c = positions[c_idx]
# find index i in BIT (1-indexed) such that prefix sum = K
i = fenwick_find_kth(bit_c, K)
original_pos = pos_c[i-1] # because pos_c is 0-indexed
# delete
fenwick_add(bit_c, i, -1)
deleted[original_pos] = True
After all queries, output: print(''.join( s[i] for i in range(n) if not deleted[i+1] ))
Edge Cases:
- When a character appears many times, and we delete them, the BIT sum reduces. The find_kth works as long as K <= total sum. Guaranteed.
Testing with sample:
Initialize:
s="abcdbcaab"
positions:
a: [1,7,8]
b: [2,5,9]
c: [3,6]
d: [4]
e..z: empty
bits: for a: size 3, BIT initially all ones. find_kth(bit_a,2) returns i=2 (since prefix sum after 2 is 2). original_pos = pos_a[1] = 7. Delete BIT index 2 (set to 0). deleted[7]=True.
Next query: 1 c: BIT_c size 2, find_kth(bit_c,1) returns i=1, pos_c[0]=3. Delete bit_c[1] (set 0). deleted[3]=True.
Query 1 d: BIT_d size 1, find_kth(bit_d,1) returns i=1, pos_d[0]=4. delete. deleted[4]=True.
Query 3 b: BIT_b size 3, find_kth(bit_b,3) returns i=3, pos_b[2]=9. delete. deleted[9]=True.
Query 2 a: BIT_a now has size 3 but only indices 1 and 3 are 1? Actually after first deletion, BIT_a at index 2 is 0. So remaining ones at indices 1 and 3. Sum =2. find_kth(bit_a,2) should return i=3. pos_a[2]=8. delete. deleted[8]=True.
Remaining: indices not deleted: 1,2,5,6 => chars: a,b,b,c => "abbc". Good.
So works.
Now we need to ensure that the find_kth function works correctly when the BIT has size maybe 1 or small. Let's test:
- If size = 1, len(bit)=2. highest power of two <= 1 is 1. idx=0, bit_mask=1, next=1 < len(bit) true, bit[1] < k? Initially bit[1] = 1. If k=1, 1<1 false, so idx stays 0. bit_mask>>=1 =>0. Return idx+1=1. Works.
- If k=1 and bit[1] >=1 (equal), returns 1.
- If k=1 and bit[1]=0? That can't happen because sum >= k, so bit[1] must be at least 1.
For size > 1, should be fine.
We also need to handle characters that have empty positions: but we never query them because operations are guaranteed correct.
Now, potential pitfalls: The BIT find_kth uses len(bit)-1 as size. For a BIT array of length sz+1, the maximum index is sz. So we compute size = len(bit)-1. Then highest power of two: we can compute bit_mask = 1 << (size.bit_length() - 1) if size>0 else 0. Since we only call find_kth when size>=1, it's fine.
We could also pass size as parameter, but we can compute inside.
Implementation of fenwick_find_kth:
def fenwick_find_kth(bit, k):
idx = 0
size = len(bit) - 1
bit_mask = 1 << (size.bit_length() - 1) # largest power of two <= size
while bit_mask:
nxt = idx + bit_mask
if nxt <= size and bit[nxt] < k:
k -= bit[nxt]
idx = nxt
bit_mask >>= 1
return idx + 1
Yes.
Now initialization of BIT:
We have for each character, after building positions list, we do:
sz = len(pos)
bit = [0]*(sz+1)
for i in range(1, sz+1):
fenwick_add(bit, i, 1)
This will call add for each i, O(sz log sz). That's fine.
But we might also consider building BIT with O(sz) by setting bit[i] = 1 and then building parents:
bit = [0]*(sz+1)
for i in range(1, sz+1):
bit[i] = 1
for i in range(1, sz+1):
j = i + (i & -i)
if j <= sz:
bit[j] += bit[i]
This builds the BIT correctly. I'll use this to save a factor of log. But we need to be careful that we don't mess up the BIT. This is a standard way to initialize a Fenwick tree from an initial array of frequencies. Since we want all 1s, we can do this. However, we need to ensure that after building, the BIT functions (add, sum) work correctly. They will, because the internal representation is consistent. This initialization runs in O(sz). So total O(n). I'll use that for performance.
So for each character c with positions list of length sz:
bit = [0]*(sz+1)
for i in range(1, sz+1):
bit[i] = 1
for i in range(1, sz+1):
j = i + (i & -i)
if j <= sz:
bit[j] += bit[i]
bits.append(bit)
But we have to store bits per character; we can store in list bits with same index.
Now we need to store the positions list as is.
Now process queries.
Now final output.
Let's code.
Potential issue: When we delete, we call fenwick_add(bit, i, -1). That will update the BIT correctly.
Now check: For each character, the BIT after initialization is as described. After some deletions, some entries become 0. The find_kth function still works.
Now, think about input reading: The first line might have s and m separated by space. Using sys.stdin.read().split() will treat them as separate tokens.
Implementation steps:
- import sys
- data = sys.stdin.read().split()
- s = data[0]
- m = int(data[1])
- queries = []
- for i in range(m):
K = int(data[2+2i])
x = data[2+2i+1] # string
queries.append( (K, x) )
- n = len(s)
- positions = [[] for _ in range(26)]
- for idx, ch in enumerate(s, start=1):
positions[ord(ch)-97].append(idx)
- bits = [None]*26
- for c in range(26):
sz = len(positions[c])
if sz == 0:
bits[c] = [] # or None, but we won't query if empty
else:
bit = [0]*(sz+1)
for i in range(1, sz+1):
bit[i] = 1
for i in range(1, sz+1):
j = i + (i & -i)
if j <= sz:
bit[j] += bit[i]
bits[c] = bit
- deleted = [False]*(n+1)
- for K, x in queries:
c_idx = ord(x)-97
bit = bits[c_idx]
pos_list = positions[c_idx]
find i
i = fenwick_find_kth(bit, K)
original_pos = pos_list[i-1]
fenwick_add(bit, i, -1)
deleted[original_pos] = True
- result = ''.join(s[i] for i in range(n) if not deleted[i+1])
- sys.stdout.write(result)
Edge Cases: If a character's BIT is empty, we shouldn't query it. But queries guarantee existence, so bit will not be empty.
Now test with sample:
We'll simulate with code later.
Now ensure that fenwick_add works: We need to pass the bit list and index and delta.
Implementation:
def fenwick_add(bit, idx, delta):
while idx < len(bit):
bit[idx] += delta
idx += idx & -idx
But note: len(bit) = sz+1. Since idx ranges 1..sz inclusive, we need condition idx <= sz, which is idx < len(bit) because len(bit) = sz+1, so idx <= sz is equivalent to idx < len(bit). So condition idx < len(bit) works.
Now fenwick_find_kth: need to use size = len(bit)-1. That is sz. The while loop uses nxt <= size.
Let's code:
def fenwick_find_kth(bit, k):
idx = 0
size = len(bit)-1
bit_mask = 1 << (size.bit_length() - 1) # highest power of two <= size
while bit_mask:
nxt = idx + bit_mask
if nxt <= size and bit[nxt] < k:
k -= bit[nxt]
idx = nxt
bit_mask >>= 1
return idx + 1
But careful: If size = 0 (empty BIT), but we won't call.
Now test with small sizes.
I'll quickly run through with sample manually to ensure find_kth works with our BIT building method.
Build BIT for a: positions [1,7,8], sz=3.
Initialize bit array of length 4 (indexes 0,1,2,3).
Step 1: for i=1 to 3: bit[i] = 1 => bit = [0,1,1,1]
Step 2: for i=1: j = 1 + (1 & -1) = 1+1=2 <=3 => bit[2] += bit[1] => bit[2] = 1+1=2
i=2: j = 2 + (2 & -2)=2+2=4 >3 => skip
i=3: j = 3 + (3 & -3)=3+1=4 >3 => skip
So final bit = [0,1,2,1]. This is the Fenwick tree for frequencies [1,1,1] (positions). Let's verify: For i=1, tree[1]=1; i=2, tree[2]=2 (sum of indices 1-2? Actually tree[2] should be sum of indices 1-2 = 1+1=2, correct); tree[3]=1 (sum of index 3 only). So works.
Now we call fenwick_find_kth(bit, 2). size=3, highest power of two <=3 is 2 (since bit_mask = 2?). Actually 3.bit_length()=2, 1<<(2-1)=2. idx=0, k=2.
- bit_mask=2: nxt=2 <=3, bit[2]=2, condition 2<2 false, so idx stays 0.
- bit_mask=1: nxt=1 <=3, bit[1]=1, condition 1<2 true => k=2-1=1, idx=1.
- bit_mask=0: loop ends. Return 2. So i=2, correct.
Now after deletion: we call fenwick_add(bit, 2, -1). Let's simulate:
bit initially [0,1,2,1].
add: idx=2: bit[2] += -1 => becomes 1. idx += lowbit(2)=2 => idx=4 >= len(bit) (4) stops (since idx < len(bit) condition false? Actually while idx < len(bit): 4 < 4 false, stops). So bit = [0,1,1,1]. That's correct: now tree representation for frequencies [1,0,1] (since we set index 2 to 0). Let's check: For frequencies: index1:1, index2:0, index3:1. Fenwick tree should be: tree[1]=1, tree[2]=1 (sum 1-2), tree[3]=1. Indeed bit[2]=1 (sum of 1-2). Works.
Now find_kth(bit,2) after deletion: size=3, bit=[0,1,1,1].
- bit_mask=2: nxt=2, bit[2]=1, condition 1<2 true => k=2-1=1, idx=2.
- bit_mask=1: nxt=3 (2+1=3), bit[3]=1, condition 1<1 false, idx stays 2.
- return 3. So i=3, correct.
So all good.
Now test with bit of size 1: positions [4] for d. sz=1. Initialize bit length 2. bit[1]=1, then building: i=1: j=2 >1 skip. So bit=[0,1]. find_kth(bit,1): size=1, bit_mask = highest power of two <=1 is 1. idx=0, k=1.
- bit_mask=1: nxt=1 <=1, bit[1]=1, condition 1<1 false, idx=0.
- return 1. Works.
Now after deletion: fenwick_add(bit,1,-1) => bit[1]=0. So bit=[0,0]. Good.
Now query processing for other characters.
Now memory: positions: list of 26 lists, each containing integers (positions). Each integer object is ~28 bytes. So for n=2e5, 2e5 ints => 5.6 MB. BIT arrays: each of total size n+26 ints = ~2e5 ints => another 5.6 MB. deleted: n+1 bool (but bools are also ints references) but memory for the list of pointers: 2e5 * 8 = 1.6 MB. So total ~13 MB plus overhead, very safe.
Thus the compressed BIT is more memory efficient.
Now check the complexity: BIT operations O(log sz) where sz <= n. So up to 18 per query. Good.
Now consider building BIT with O(sz) method: That's fine.
Now code details:
- Use ord conversion for speed.
- Use local variables for functions to avoid global lookups? Might not be necessary.
Now we also need to ensure that we treat indices properly. We'll use 1-indexing for BIT and for positions list referencing original 1-indexed positions.
Now test with more cases.
Case: s = "aaaaa", m=2 queries: 2 a, 2 a
positions a: [1,2,3,4,5], sz=5.
BIT initially built.
First query: K=2 => i=2, pos=2, delete.
After deletion: frequencies: [1,0,1,1,1] (positions: 1,3,4,5 remain). BIT updated.
Second query: K=2 => now 2nd remaining: positions: 1st at 1, 2nd at 3? Actually order: remaining indices: 1,3,4,5. So 2nd is 3. So find_kth should return i=3? Because in BIT over list indices 1..5, after deletion indices 2 is 0. So we need to find the index in the list (i) such that prefix sum = 2. The list order: index1 (pos1) is 1, index2 (pos2) is 0, index3 (pos3) is 1. So prefix sums: after index1 sum=1, after index2 sum=1, after index3 sum=2. So i=3. Good. Then original_pos = pos_list[2] = 3. Delete. So final positions: 1,4,5 => "aaa". So output "aaa". Works.
Edge: Deletion of last occurrence: find_kth works.
Now, what if there are queries for characters that appear many times and we delete them multiple times; BIT works.
Now we need to be careful about the initial building of BIT: We set bit[i] = 1 for all i, then build parents. But does this correctly build the BIT? Let's verify for a larger example.
Suppose sz=5, initial frequencies all 1. After setting bit[i] = 1 for i=1..5, we have bit array: [0,1,1,1,1,1]? Actually length=6 (indexes 0..5). Then we run for i in 1..5:
i=1: j = 1+1=2 <=5 => bit[2] += bit[1] => bit[2]=1+1=2
i=2: j = 2+2=4 <=5 => bit[4] += bit[2] => bit[4]=1+2=3? Wait bit[4] initially 1, after addition becomes 1+2=3.
i=3: j = 3+1=4 <=5 => bit[4] += bit[3] => bit[4]=3+1=4
i=4: j = 4+4=8 >5 skip
i=5: j = 5+1=6 >5 skip
So final bit = [0,1,2,1,4,1] (indexes 0..5). Is this the correct Fenwick tree for frequencies [1,1,1,1,1]? Let's compute expected Fenwick tree:
Index 1: sum of range (1-1) => 1
Index 2: sum of range (1-2) => 2
Index 3: (3-3) => 1
Index 4: (1-4) => 4
Index 5: (5-5) => 1
So expected: [0,1,2,1,4,1] exactly. So the build works.
Now after some deletions, we use add function to update. That works.
Thus, this approach is solid.
Now we should implement.
Potential issue: Input reading: The first line contains the string s followed by an integer m. Could be separated by space or newline? Using read().split() covers both.
Now I'll write final Python code.
But note: The constraints: m up to 40000, but the number of characters in the string up to 200k. So we can process.
One more nuance: The queries are given as "K x" where x is a character. In the input, the character might be separated by spaces. So reading tokens works: after reading m, we have 2*m tokens: each pair is (K, x). So we can parse.
Now, we need to make sure we convert K to int.
Now code.
We'll define functions inside main or globally.
Now test with sample.
Let's implement and run mentally.
Alternatively, I could produce code in the answer.
Now also consider that for characters that have empty list, we set bits[c] to an empty list or None. But we never query them. However, if we accidentally query (shouldn't happen), we would get error. But it's safe.
Now I'll write the solution.
Potential performance improvements: Use list comprehension for building positions. Use sys.stdin.buffer.read() for faster input.
But overall fine.
Now, I'll also note that we could avoid storing deleted array by directly marking the position as removed in some other way, but deleted array is fine.
Now code.
Pseudo:
import sys
def fenwick_add(bit, idx, delta):
while idx < len(bit):
bit[idx] += delta
idx += idx & -idx
def fenwick_find_kth(bit, k):
idx = 0
size = len(bit) - 1
bit_mask = 1 << (size.bit_length() - 1)
while bit_mask:
nxt = idx + bit_mask
if nxt <= size and bit[nxt] < k:
k -= bit[nxt]
idx = nxt
bit_mask >>= 1
return idx + 1
def main():
data = sys.stdin.buffer.read().split()
s = data[0].decode()
m = int(data[1])
queries = []
idx = 2
for i in range(m):
K = int(data[idx]); x = data[idx+1].decode(); idx += 2
queries.append((K, x))
n = len(s)
positions = [[] for _ in range(26)]
for i, ch in enumerate(s, 1):
positions[ord(ch)-97].append(i)
bits = [None]26
for c in range(26):
sz = len(positions[c])
if sz == 0:
bits[c] = [] # empty
else:
bit = [0](sz+1)
for i in range(1, sz+1):
bit[i] = 1
for i in range(1, sz+1):
j = i + (i & -i)
if j <= sz:
bit[j] += bit[i]
bits[c] = bit
deleted = [False]*(n+1)
for K, x in queries:
c_idx = ord(x)-97
bit = bits[c_idx] # should not be empty
pos_list = positions[c_idx]
i = fenwick_find_kth(bit, K)
p = pos_list[i-1]
fenwick_add(bit, i, -1)
deleted[p] = True
result = ''.join(s[i] for i in range(n) if not deleted[i+1])
sys.stdout.write(result)
if name == "main":
main()
We need to be careful about decoding bytes: When using sys.stdin.buffer.read().split(), the tokens are bytes. So we decode the string s and the character x. Alternatively, we can just use sys.stdin.read() which returns string, but buffer is faster. I'll use buffer.
But note: The character x is a single byte (like b'a'), we can decode or convert to char using chr(x[0])? Actually data[2] etc are bytes. Since they are single character, we can do x = data[idx+1].decode() or just x = data[idx+1][0] and then use chr? But easier: decode to string. So decode.
Now test sample:
data: [b'abcdbcaab', b'5', b'2', b'a', b'1', b'c', b'1', b'd', b'3', b'b', b'2', b'a']
s = 'abcdbcaab', m=5. queries parsed.
positions built.
bits built.
process queries.
result = 'abbc'
output.
Works.
Now consider large input: it should be fine.
Now we also need to think about the case where the BIT find_kth may need to handle k exactly equal to sum. That's fine.
Now one more nuance: In fenwick_find_kth, we compute bit_mask as 1 << (size.bit_length() - 1). But what if size = 0? Then size.bit_length() returns 0, and (0-1) would be negative, causing error. But we never call for size 0. However, to be safe we could handle: if size == 0: return 0. But not needed.
Now we also need to ensure that we handle the case when the BIT is empty. But again not needed.
Now, we could also create a mapping from character to index once.
Now, final answer.
But there is an alternative simpler approach: Use 26 sets or sorted lists? But we need dynamic order statistics. BIT is appropriate.
Now we can produce final solution explanation.
Now let's reflect: The problem is from some contest, maybe Codeforces? The approach with per-character BIT is standard.
Now consider potential time: The BIT find_kth uses a while loop over bits; for size up to 2e5, bit_mask goes down from 2^17=131072 to 1, about 17 iterations. Good.
Now we could also implement the find_kth using binary search on BIT sums, but binary lifting is fine.
Now memory: using compressed BIT is efficient.
Now think about further optimization: We might not even need a global deleted array; we could instead keep a set of deleted positions and at the end exclude them. But deleted array is fine.
Now one more nuance: The positions list for each character is static, we don't modify it. When we delete the K-th occurrence, we only mark the original position as deleted. The BIT handles the count.
Now confirm that we do not need to handle shifting of indices because we are referencing original positions. At the end, we output characters in original order skipping deleted ones. That yields correct final string because deletions don't change relative order of remaining characters. So it's fine.
Now final answer.
But wait: There is a subtlety: When we delete a character, do the positions of later characters shift? In the final string, the order is based on the original indices because we are outputting in original order. If we delete some characters, the relative order of the remaining characters remains the same as original order. So indeed we can just filter out deleted positions.
Thus approach is correct.
Now we can write the final solution.
Now let's produce final answer.
But also consider if we had to process queries online (like after each query we might need something), but final output only needed.
Now code as above.
Potential micro-optimizations: Use local variables for functions inside main (like assign to local variables for speed). But not needed.
Now I'll produce the final answer with explanation.
But the problem statement might have input where m is on the next line after string? The first line contains the string s followed by an integer m. It's ambiguous but reading all tokens works.
Now final solution.
But I'll test with additional cases.
Case 1: s = "a", m = 1, query: 1 a. After deletion, string empty. Our code: positions: a: [1], BIT size 1. find_kth(bit,1) => i=1, p=1, delete bit, deleted[1]=True. result: filter: s[0] (i=0, i+1=1) if not deleted[1] => False, so result = ''. join => empty string. Output should be nothing. That's fine.
Case 2: s = "abcabc", m=3: queries: 1 a, 2 b, 3 c. After: initial positions: a:1,4; b:2,5; c:3,6. Delete 1st a => pos1. Delete 2nd b => remaining b: positions 2,5? After deletion, b count: originally 2. Delete 2nd b => which is pos5? Actually after deletion of a, b positions unchanged. The 2nd b is at pos5. Delete pos5. Delete 3rd c? There are only 2 c. But operation guaranteed correct, so ignore.
But let's test valid: 1 a (delete pos1), 1 b (delete first b pos2), 1 c (delete first c pos3). Remaining: pos4 a, pos5 b, pos6 c => "abc". Our code would work.
Now case where multiple deletions of same character.
Thus final.
Now I'll write final answer with explanation.
But the problem says: "Given a string s and m queries. For each query delete the K-th occurence of a character x." The queries are given one per line. Sample input shows string and m on same line but then m lines follow. So reading tokens works.
Now produce final solution.
Potential pitfalls: The BIT find_kth function might be off if the BIT is not built exactly as described? But we tested.
I'll include in the code a check: if size==0: return 0 but not used.
Now final answer.
Let's also consider using array module to store BIT for memory? Not needed.
Now final.
I'll produce explanation.
In explanation, I'll describe: Use original positions, for each character maintain Fenwick tree over its occurrences to support order statistics and deletions. Finally output characters not deleted.
Now code.
Will output as required.
Now I'll produce final ChatGPT answer: explanation + code. We can solve the problem efficiently using Fenwick trees (Binary Indexed Trees) per character.
Since deletions do not change the original order of the remaining characters, we can work with the original indices.
Approach
- Preprocess the string: for each character (a–z), store the list of its occurrence positions (1‑based) in increasing order.
- For each character, build a Fenwick tree over its occurrence list, initially with all entries set to
1 (meaning the occurrence is still present).
- Process each query
(K, x):
- Use the Fenwick tree of character
x to find the index i (in the occurrence list) of the K‑th remaining occurrence.
This is done by a standard find‑Kth operation on the Fenwick tree.
- Retrieve the original position
p = positions[x][i-1].
- Mark position
p as deleted (deleted[p] = True) and update the Fenwick tree by adding -1 at index i.
- After all queries, reconstruct the answer by scanning the original string and keeping only characters whose positions are not marked as deleted.
All operations are O(log n) per query, and the memory used is linear in the length of the string.
import sys
# Fenwick tree helpers
def fenwick_add(bit, idx, delta):
"""add delta at position idx (1‑based)"""
while idx < len(bit):
bit[idx] += delta
idx += idx & -idx
def fenwick_find_kth(bit, k):
"""return smallest idx such that prefix sum >= k (1‑based)"""
idx = 0
size = len(bit) - 1
# highest power of two not exceeding size
bit_mask = 1 << (size.bit_length() - 1)
while bit_mask:
nxt = idx + bit_mask
if nxt <= size and bit[nxt] < k:
k -= bit[nxt]
idx = nxt
bit_mask >>= 1
return idx + 1
def main():
data = sys.stdin.buffer.read().split()
s = data[0].decode()
m = int(data[1])
queries = []
idx = 2
for _ in range(m):
k = int(data[idx])
x = data[idx + 1].decode()
idx += 2
queries.append((k, x))
n = len(s)
# positions[c] = list of indices (1‑based) where character c occurs
positions = [[] for _ in range(26)]
for i, ch in enumerate(s, 1):
positions[ord(ch) - 97].append(i)
# Fenwick trees for each character (built in O(occurrences))
bits = [None] * 26
for c in range(26):
sz = len(positions[c])
if sz == 0:
bits[c] = [] # never queried
else:
bit = [0] * (sz + 1)
# initialise all frequencies to 1
for i in range(1, sz + 1):
bit[i] = 1
# build Fenwick tree in O(sz)
for i in range(1, sz + 1):
j = i + (i & -i)
if j <= sz:
bit[j] += bit[i]
bits[c] = bit
deleted = [False] * (n + 1) # 1‑based deletion marker
for k, x in queries:
c_idx = ord(x) - 97
bit = bits[c_idx] # non‑empty by problem guarantee
pos_list = positions[c_idx]
# index (1‑based) in the occurrence list of the k‑th remaining char
i = fenwick_find_kth(bit, k)
p = pos_list[i - 1] # original position in the string
fenwick_add(bit, i, -1) # delete it
deleted[p] = True
# reconstruct the final string
result = ''.join(s[i] for i in range(n) if not deleted[i + 1])
sys.stdout.write(result)
if __name__ == "__main__":
main()