Inversions Organize
InterviewTime limit20sMemory limit1024 MB
Given a 2N by 2N grid of I and O letters, find the fewest cell flips so the top and bottom halves have equal I counts and the left and right halves do too.
- Level
Medium5 of 10
- Topics
- Math, Matrix, Implementation
- Solved
- No attempts yet
Problem
After the trouble with printing advertising for IO two years ago, the conference marketing team decided to use an interactive installation. It consists of a matrix of rows and columns of touchscreens. Each touchscreen can display either an uppercase I or an uppercase O. When one of the screens is touched, it switches to the letter it was not displaying right before the touch.
The installation you are looking at is disorganized. You want to change some letters so that the top rows show the same number of I's as the bottom rows, and the leftmost columns show the same total number of I's as the rightmost columns.

For example, in the left picture above, . The top 2 rows show 3 I's in total, while the bottom 2 rows show 5. Both the leftmost 2 columns and the rightmost 2 columns show 4 I's. By touching the two highlighted screens, the state changes to the one in the right picture. It shows 4 I's in the top 2 columns and in the bottom 2 columns, and it keeps the left and right sides balanced.
Given the state of the installation, find the minimum number of letter changes needed to reach the goal.
Input
The first line of the input gives the number of test cases, . test cases follow. Each test case starts with a line containing a single integer , half the number of rows and columns of the matrix. Then, lines follow. The -th of these contains a string of characters . is the letter currently displayed on the screen in the -th row and -th column of the matrix.
Output
For each test case, output one line containing Case #x: y, where is the test case number (starting from 1) and is the minimum number of touches required to make the installation display the same number of I's in its top and bottom halves, and the same number of I's in its left and right halves at the same time.
Limits
.
For all , is either an uppercase I or an uppercase O.
Hints
Sample Case #1 is the one explained in the statement. Not touching anything does not work, and a single touch would leave an odd number of I's in total, so the result cannot be balanced. The statement explains how to balance it with two touches (there are other ways).
In Sample Case #2, changing the top left corner to O leaves no I, so all halves have the same amount (0).
In Sample Case #3, the installation already meets the requirements, so no touch is needed.