I'm looking for a data structure or subroutine that takes in a sorted list $$$L$$$ of $$$n$$$ integers and a list $$$Q$$$ of $$$n$$$ integers. For each element $$$q\in Q$$$, we should report the largest remaining element in $$$L$$$ smaller than $$$q$$$ and then remove it (or we can report $$$-1$$$ if no such integer exists). I would like the entire process to take $$$O(n \log n)$$$ time.
My understanding is that this approach is necessary for today's 2254E - Chronostasis, but many user-accepted Python solutions seem to implement Fenwick trees, which I believe might be too complicated for a Div. 3 contest and not the intended solution (though I could be wrong).








dsu i guess
Could you elaborate a bit more? Are you taking the union of consecutive "runs" of integers that are removed from $$$L$$$? How would the query procedure work?
You can just do
unite(index,index+1)And the query is
dsu.find_parent(index)with path compressionOh so the path compression is being used to efficiently map each index to its largest available predecessor, such as in 385671202
First time I've seen this -- very clean and cool!
std::multisetcan do this.Hm, do you know if there's a similar data structure in Python?
If I am not mistaken, Python does not have built-in structures similar to std::set or std::multiset unless you use external libraries (which isn't possible on Codeforces). I would recommend either solving the problem with a different language like C++, or if you really want to remain Python-only, you can implement something similar for your specific use case.
For this specific scenario you provided, I would recommend either of the following:
Not sure if there is something easier for pure Python; would be curious to hear if there is, though.
There is actually something pure Python, but not native, it's called Sorted List and is available in a python module named "sorted_containers".
This module is actually imported for you on Atcoder and Leetcode, it's not the case for codeforces tho. So what I usually do, is copy paste the implementation.
I don't use Python often so I didn't know about that, thanks for sharing!
Though I guess the downside is that the implementation is huge if you're in some sort of offline contest and copy-paste isn't allowed.
Thanks for the replies! I found a relatively short implementation of Sorted List (along with other suggestions about how to implement dynamic BST, including the above path compression idea) at https://codeforces.me/blog/entry/89170
The ~200-line Python implementation they suggested, in https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py, is pretty short and easy to adapt. A possible downside is that it seems the update time is $$$O(n^{1/3})$$$ to $$$O(n^{1/2})$$$, but I was able to at least get it working under the time limit for this problem.
U need to use binary search + multiset, multiset supports deletions in O(log n).