Pile of Cubes
Time limit1sMemory limit128 MB
Find the largest number of cubes in a gravity-respecting pile that matches the given top, front, and right views, or report -1 when no pile fits.
Problem

The figure above shows a pile of cubes seen from an angle. The first floor holds 8 cubes, the second floor holds 4, and the third floor holds 1. Looking at this pile from the top, from the front, and from the right side gives the three pictures below, called the top view, the front view, and the right side view. None of the three views rotates the pile.

Read the other way around, three such pictures let you guess the pile they came from. Many different piles look the same from the top, the front, and the right side.
Write a program that computes the largest number of cubes a pile can use while still looking exactly like the three given views.
Some triples of pictures come from no pile at all. Gravity applies here as it does on Earth, so every cube rests on the ground or on another cube. Your program also has to decide whether the three pictures are possible in the first place.
Input
The first line contains the number of test cases ().
The first line of each test case contains the picture size (), and all three pictures are . The next lines hold the top view, the front view, and the right side view in that order. Each picture is an matrix of 0s and 1s, one matrix row per line, with entries separated by a single space. A 0 means no cube is seen at that position and a 1 means a cube is seen.
The matrices line up with the pile as follows. Split the ground into cells, number the rows to from the back to the front, number the columns to from the left to the right, and let be the number of cubes stacked on cell .
- Row , column of the top view is 1 exactly when .
- In the front view the upper rows are the higher floors, so row stands for floor , and column stands for the -th ground column from the left. Row , column is 1 exactly when some cell of that ground column carries at least cubes.
- In the right side view the upper rows are the higher floors as well. Column from the left stands for the ground row that is -th from the front, which is row . Row , column is 1 exactly when some cell of that ground row carries at least cubes.
Output
For each test case print one line. Print the largest number of cubes used by a pile that looks exactly like the three given views, or when no pile looks like them. The empty pile counts as a pile, so three all-zero pictures give .