Editorial
Let the resulting grid be .
The key condition is
If this condition fails at some , take the same path up to , then use Right-Down on one path and Down-Right on the other, and use the same suffix from . The only different visited cells have equal characters, so the two paths produce the same string.
Conversely, consider two distinct shortest paths and the first point where their moves differ. Their next cells are some and . The condition makes these two characters different, so the two path strings are different.
Thus the grid is not cool if and only if the condition holds everywhere.
Cells with the same value of form an anti-diagonal. The condition says that each anti-diagonal must alternate between and . Each anti-diagonal therefore has exactly two valid patterns, and different anti-diagonals are independent.
Consider one anti-diagonal of length . Use as a reference pattern, and let be the number of cells on this anti-diagonal where differs from . Choosing the reference pattern costs flips, while choosing its complement costs flips.
The minimum cost on this anti-diagonal is
and switching to the more expensive choice adds
Let be the sum of all minimum costs. Since the anti-diagonal lengths sum to , the maximum possible cost is .
It remains to show that every integer between these two bounds is attainable. Sort the anti-diagonals by nondecreasing length. For an anti-diagonal of length , the value has the same parity as and satisfies . Before the first anti-diagonal of length , there are two anti-diagonals of each smaller length. Length contributes , and every odd length contributes at least . Therefore, if is the sum of previous weights, then . Later anti-diagonals of the same length only increase . Hence
always holds.
If the previous weights can make every subset sum from through and the new weight satisfies , then after adding it every value from through is attainable. Induction from the first length- anti-diagonal proves that the subset sums of all weights form one continuous interval.
Therefore, a solution with exactly flips exists if and only if
To construct the choices, store prefix sums of the sorted weights and set . Process the weights in reverse order. If the current is larger than the sum of all previous weights, the current weight must be selected; switch this anti-diagonal to its more expensive pattern and subtract from . Otherwise keep the cheaper pattern. The interval property guarantees that this ends with .
One scan of the grid computes and for every anti-diagonal, followed by sorting anti-diagonals. The time complexity is , and the auxiliary memory complexity excluding the output grid is .
Solution written by GPT5.6