Editorial for WC '15 Finals S2 - Hydration


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.

If it's possible for the cows to all get a drink, then it must be doable in at most N minutes. If it's possible for them to finish drinking in m minutes, then it must be possible for them to finish in m+1 minutes. This means that we can binary search for the answer on the [1, N+1], and if it's impossible in even N minutes, we'll get a result of N+1 and can output -1 instead.

What remains is being able to determine whether or not the cows can all have a drink within m minutes. In particular, we would like to know if there exists a way to assign the cows to the troughs such that each trough is assigned at most m cows, and that each cow i's assigned trough j satisfies C_i-K \le T_j \le C_i.

If cow a is shorter than cow b, then intuitively, we should never assign cow a to a taller trough than cow b because otherwise they could be swapped for a better configuration. This idea suggests a greedy algorithm.

Assuming that the heights of the cows and troughs have both been sorted in non-decreasing order (respectively doable in time complexities \mathcal O(N \log N) and \mathcal O(M \log M)), we can iterate over each cow i in order, assigning it to the first trough j that it can validly drink from (if any). In other words, we're looking for the smallest j such that C_i-K \le T_j \le C_i, and fewer than m cows have been assigned to drink from trough j so far.

As we iterate i from 1 to N, note that j will never decrease. Therefore, we only have to keep track of the current value of j and the number of cows c that have been assigned to trough j, for each cow i, we'll first increase j as long as it's invalid (resetting c to be 0 whenever j is increased), and then assign cow i to it (increasing c by 1). If j exceeds M, then we'll know that there was no valid trough, meaning that not all of the cows can drink within m minutes. The total time complexity of this algorithm is therefore \mathcal O((N+M) \log N + M \log M).


Comments

There are no comments at the moment.