## Editorial for DMOPC '21 Contest 8 P2 - Kanna Market

**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.**

Author:

## Hint

Think about columns. Specifically, can we consider even and odd columns separately?

## Subtask 1

The key observation for this problem is that it is necessary and sufficient for columns with the same parity to have the same sum.

Why? Well, consider a grid:

```
a b c
d e f
```

Then:

Or:

Once we've realized this, we can iterate through all possible sums from to . For each column, if there are two zeroes, we can either use a formula, or pre-calculate how many ways there are to fill in the two cells. If there are two elements, then we check that they sum to . If there is one, we check that it is not too large and not too small so that we can fill in the other cell to make the column sum to .

## Subtask 2

We need a few optimizations here. Assume we are considering the columns independently. First, instead of iterating from to , let's make a single pass through the grid, and calculate the minimum possible sum and maximum possible sum.

Then clearly if there are two or one elements in a column, there is only one way to fill that column to obtain any desired sum. If there are no elements filled in, we can use a formula to calculate, given , the number of combinations.

To come up with this formula, note that , , and . Also, in general if we increase our combination count either goes up or down by . We want a formula that is the minimum of two lines, one of slope and the other of slope . It may be helpful to simply guess a formula and check if it's right. At any rate, in this case our formula is .

Once we have come up with our minimum sum and maximum sum , we can use our formula and raise it to the power of the number of zeroes, in order to calculate quickly the number of combinations.

## Tricky Cases

If one column has two filled in numbers that sum to, for instance, , and another column has a single , then this is impossible, since there is no number we can pair with the to get .

Similarly, if two filled in numbers sum to and another column has a single , this is impossible.

If two columns are both filled completely, we must ensure they have the same sum.

One simple way to consider all these cases is to set to start. Then, if we see a column with one filled element, set , . If we see a column with two filled elements, set and .

## Comments