Editorial for WC '16 Contest 2 S2 - Away Mission


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's first consider the case in which Q = 1. We want to assemble shirts with triples of CCC values (r, g, b) such that, for as few of them as possible, r > m, where m = \max(g, b).

For starters, let's just consider forming pairs of the green and blue CCCs (g, b), with the goal of maximizing their resulting m values. If we consider the list of all 2N green/blue CCC values, the best we could ever hope to do is for the largest N of these 2N values to be equal to the N produced m values. As it turns out, this can always be accomplished – for example, if we pair the largest green CCC with the smallest blue CCC, the second-largest green CCC with the second-smallest blue CCC, and so on. As such, if we sort these 2N values and take the largest N of them, we'll get an optimal set of m values.

What remains is pairing the r values against these m values, which can be done greedily. Assuming that both lists are sorted in non-decreasing order, let's iterate upwards through the r values. For a given r value, we might as well match it with the smallest remaining m value which is larger than or equal to it, if any. This can be done by maintaining a pointer into the sorted list of m values, and advancing it forwards at each step until a sufficiently large m value is reached (or until it hits the end of the array, at which point no more non-red shirts can be created).

The other case, in which Q = 2, is similar – we now want to maximize the number of triples in which r > m. This time, we'll want to form N (g, b) pairs with the goal of minimizing their resulting m values. If we consider the largest of all of the green or blue CCC values, it will necessarily need to be one of the m values. It'll need to be matched with some value from the opposite list, so we might as well pair it with the largest of those, in an effort to minimize future m values. Therefore, it's always optimal to pair the largest green and blue CCCs together, and this can be extended to show that we should always sort the lists of green and blue CCC values independently, and then pair them up in that order to compute an optimal set of m values.

At that point, we can follow a very similar algorithm to the Q = 1 case in order to greedily pair up the r and m values, this time iterating downwards through the r values and matching each one against the larger remaining m value which is smaller than it (if any).

The time complexity of this algorithm in either of the two cases is dependent on sorting \mathcal O(N) component values. This can be done in \mathcal O(N \log N) time, or \mathcal O(N) time if we take advantage of their limited magnitudes with radix sort.


Comments

There are no comments at the moment.