Editorial for DMOPC '21 Contest 3 P6 - Good Grids
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
Note that the condition on good grids is equivalent to every
For an
Observe that the condition implies that these bolded edges form a matching in this
We can initialize the weight of all these edges to
- We reduce the problem to finding a maximum weight perfect matching in a bipartite graph. Colour the vertices of the inner
by grid black and white in a checkerboard pattern (say, the top-left vertex is white). In addition to the weighted edges that connect two adjacent vertices, we add an edge between each black vertex and white vertex on the perimeter of the inner by grid with weight equal to the sum of the weights of the edges that connect or to the perimeter of the by grid. If and/or is a corner vertex, we only take the maximum such weight. Finally, if is odd, we add another black vertex and connect it to all boundary white vertices , with weight equal to the weight of 's perimeter-touching edge. Now any perfect matching in this bipartite graph corresponds to a valid matching as needed. - Based on the solution above, instead of adding an edge between all pairs of differently coloured boundary vertices, consider the min cost max flow network formed by the weighted bipartite graph of the inner
by grid. We add an extra vertex to this graph, and connect all left side boundary vertices with with capacity and cost equal to the negative of the weight of 's perimeter-touching edge. Similarly, we connect to all right side boundary vertices with capacity and cost equal to the negative of the weight of 's perimeter-touching edge. If is odd, we add another node to the smaller side and connect it with with capacity and cost , as well as to the source or sink. Now any max flow in this graph corresponds to a valid matching as needed, and this solution requires slightly fewer edges than the solution above. - Finally, we can model the conditions directly using flows with lower bounds. We can build the usual maximum weight matching min cost max flow network from the entire
by grid and force all inner vertices to be matched with a lower bound of on the edge that connects it to the source or sink. Then, we can reduce this network to one without lower bounds (see cp-algorithms for more details) and run a min cost max flow algorithm on it.
All of these solutions need
Remark: It is possible to make min cost max flow algorithms that use SPFA run in its worst case
To construct the good grid from the matching, consider drawing an arrow between any two adjacent cells pointing right or down. Label each arrow with a
Now for each matched edge, replace the corresponding arrow's weight with a
Observe that since the matching satisfies the conditions, for any A
, B
, or C
to this cell depending on this value modulo
Another way to construct the good grid is to set the top-left
Time complexity:
Comments