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.
Let
be the volatility of students
. The volatility of a set of students is simply the number of students
who cannot be coerced into using their phones by anybody else (in other words, the number of students
for which there exists no student
such
and
). We can thus think of each student as contributing either
or
volatility to each
value. Let
be the smallest value of
which satisfies the above conditions (or
if there's no such
). If
, then student
contributes no volatility at all, and otherwise, they contribute
volatility to each of the values
. So, if we had the values
, we could use them to compute the volatilities
with a simple
sweep.
What remains is computing the values
efficiently. Let's process the
students in decreasing order of
value, either by explicitly sorting them by their
values, or by keying them by their
values and then iterating over all possible
values from
down to
. Let
be the minimum index (in the original ordered student list) of any student processed so far whose range of influence includes desk
(or
if there's been no such student so far). When processing student
, we can observe that
must be equal to
. And upon finishing with student
, we should update
to
for each desk
in the inclusive interval
.
Let's maintain the values
(where
is the maximum possible
value) using a segment tree with lazy propagation, in which each node stores the minimum value of any
value in its interval, as well as the minimum new value which all
values in its interval should lazily be updated with. This allows us to both query an
value and update a range of
values as necessary in
time each, resulting in an overall time complexity of
(where
is the maximum possible
value and
is the maximum possible
value).
Comments