Editorial for COCI '23 Contest 3 #3 Milano C.le
Submitting an official solution before solving the problem yourself is a bannable offence.
We will use the notation from the task text: is the order in which the trains arrived at the station on
the first day, and
is the order in which the trains left the station on the second day.
Let's create a sequence , such that
is equal to
for which
. In other words, sort the order of
departure of trains according to the order of arrival of trains.
For example, let the order of arrival of trains be 3 5 2 4 1
, and the order of departure 3 2 5 1 4
. Then
because
,
because
,
because
,
because
, and
because
. Therefore, the sequence
4 5 3 1 2
.
Let's now look at the trains in the sequence . In the example above, trains
and
cannot be on the
same platform because
, which means that train
would have to leave the station before train
,
which is impossible because train
arrived at the station before train
. On the other hand, trains
and
can be on the same platform because
, which means that train
will want to leave the
station before train
, which is possible because train
arrived at the station after train
. From this it
follows that if we were to find a sequence such that
, then we would need
platforms
for those trains.
We have now reduced the task to finding the longest such sequence. This problem is known as the longest
increasing subsequence. The solution to the task is the length of the longest increasing subsequence of the
sequence . Note that the trains contained in that subsequence will be the first train on each of the
platforms, and that it is possible to arrange the other trains on the platforms so that all trains can leave
the station without being blocked by other trains. The overall time complexity is
.
Comments