ACM ICPC World Finals 2017

Problem C: Mission Improbable

Shortest judge solution: 818 bytes. Shortest team solution (during contest): 1178 bytes.

Python solutions by the judges: both Pypy and CPython

If not for the top-down view, this problem would be really straightforward. Since solving easy problems is easier than solving harder problems, let’s go over that first.

Consider the highest stack of crates in the input, and assume it has height H1. It has to appear both in the front view and the side view at least once. Assume that it appears m1 times in the front view, and n1 times in the side view, and without loss of generality, assume n1 ≤ m1. In that case, we will need at least m1 stacks of height H1, and we can achieve the correct side and front view by arranging m1 stacks so that there is at least one in each of the m1 columns and n1 rows.

Then, proceed to the next height, H2. Again, we have m2 columns and n2 rows that have to contain a stack with height H2. The one thing that is different here is that it is possible for, say, m2 to be zero – in which case we will put the stacks of height H2 in the column(s) already containing stacks of height H1. Following this pattern, we will use up a total of

∑ Hi · max(mi, ni)

crates. After placing all the crates for all the heights, the side and front views are already correct, so (disregarding the existence of the top view) we can just leave the remaining spaces empty.

Now, the existence of the top view changes two things in that strategy. First, at the end, we might have to leave a single crate (instead of zero crates) in some of the remaining spaces, to prevent the top view from noticing the spaces are empty. This is easy – we just keep track of how many spaces we filled, and then add to the final answer the number of spaces seen in the top view minus the number of spaces already filled.

The more tricky part is that due to the top view seeing empty spaces in some spots, it might be impossible to put a stack of height Hi in each of the mi columns and n1 rows using just max(mi, ni) stacks. We want to have as many stacks as possible to cover both a row and a column, and then we can make the remaining columns and rows covered by just putting a stack of height Hi wherever it was in the original input. Notice that this is a bipartite matching problem – we have a set of rows and a set of columns, and we can connect a row to a column when the top view shows a non-empty stack. So, for each height Hi appearing in the input, we run bipartite matching to find out how many stacks can cover both a row and a column, and then replace max(mi, ni) with mi + ni − Bipartite(i). Note that this formula works fine even if one of the sides is zero. Since the runtime of bipartite matching is super-linear, the worst-case for this problem is if all the columns and rows in the front and side views are of the same height. With r, c ≤ 100, this will easily run in time.