## Editorial for CCC '19 S3 - Arithmetic Square

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

We will not cover solutions to subtasks in this editorial. This may change in the future based on demand.

Note firstly that if a row or column has two integers that are filled in, the third one can be filled in directly, irrespective of whether it's adjacent to both of them or exactly one of them. We will assume that after filling in any given integer, this principle is applied.

For many grids, blindly applying this rule repeatedly will result in filling in the grid. There are only two cases remaining:

The first case is where a row or a column is completely filled in. Assume without loss of generality that a row is filled in. If no other entry is filled in, then we can duplicate the row twice. Otherwise, the grid looks something like this:

Take the first row, increment everything by , and place in on the second row, do the same for the third row except increment by .

The second case is where no row or column is filled in:

Consider the following 3 by 3 grid:

Note that irrespective of how we choose the initial values of , , , and , we can always generate a valid square. Therefore, if all the known values fit in a square, we can fill in the remaining values arbitrarily, and generate the square from there!

The only cases left to handle are the following:

In the first case, you can set the middle element equal to . In the second case, set one of the elements adjacent to both and equal to .

## Comments

Note that this problem can be solved efficiently using elimination. Also, testing random numbers can pass.

The elimination solution in your link passes all test cases, including the additional cases. But I found a bug in the code. (line 178)

Consider the following input:

That program outputs:

That bug has been fixed. See this submission: https://dmoj.ca/src/2138481

It solves a linear system of 4 variables and 8 equations in the worst case, instead of the original 9 variables and 15 equations.

From the second matrix in the editorial, one can see all valid solutions can be determined with 4 variables, which are , , , and in the matrix.

In my new solution, I express the solution in this form:

My code solves for the coefficients , , , and and determine the solution.

EDIT:Although I know my code doesn't always work, I tested randomly generated cases and it fails none of them. If someone could give one not-working case I'd appropriate.This comment is hidden due to too much negative feedback. Click here to view it.

This comment is hidden due to too much negative feedback. Click here to view it.

Thank you, Mr. Troy Vasiga.

🙏