Editorial for COCI '22 Contest 4 #5 Vrsta


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

First, let us notice that we are only interested in the height of a student leading the warm-up. We can just track the height and the number of students of that height. We can compress the heights of students because to determine the height of a student who will lead the warm-up, we only need to know how many students are taller and how many are shorter than him. So now the student heights are numbers from 1 to 200\,000. We can now go through the order of students entering the gymnasium and will update the segment tree. The i^\text{th} leaf of the segment tree will track the current number of students of height i in the gymnasium. The values of other nodes will be the sum of the children's values. If the current number of children is x, then the warm-up will lead \lfloor \frac x 2 \rfloor^\text{th} child in a sorted line. Let that number be y. Now let's determine the height using the segment tree. Start from the root of the segment tree and use this algorithm until you reach the leaf: If the value of the left child is greater or equal to y, then go to the left child. If the value is smaller than y, then reduce the y by the value of the left child and go to the right child. The leaf index will be the compressed height of the required height. Total time complexity is \mathcal O(n \log n).


Comments


  • 0
    Ivan_Li  commented on Dec. 5, 2023, 1:19 p.m.

    You can also solve this using an order statistics tree (implemented with fenwick tree), which has a better constant factor than segment tree.