Grid Aliens
Time limit1sMemory limit256 MB
Assign each cell of an N by N grid to one of two regions to maximize node rewards minus the cut edge costs.
- Level
Medium7 of 10
- Topics
- Graph
- Solved
- No attempts yet
Problem
On one planet every alien lives on a point of an grid. Some aliens like water and some do not. This tendency is called the hydrophilic property, and alien has its own degree , a real number with . An alien that sits away from the border has 4 grid neighbours (up, down, left, right). An alien on a border edge has 3 neighbours, and an alien on a corner has 2.
The friendship of two neighbouring aliens and comes from the two hydrophilic degrees and .
If two neighbours have the same hydrophilic degree, the friendship is perfect, . The critical situation happens when and . Friendship is not defined for a pair that is not adjacent, such as and in Figure 1.
The aliens decided to put up separating fences to reduce the conflicts between groups with different hydrophilic degrees. They first split the grid space into two disjoint regions: the W region for hydrophilic aliens, and the Q region for hydrophobic aliens, who dislike a watery environment and have small hydrophilic degrees. Then they build a closed fence around the Q region to keep conflicting aliens apart. The dotted red curves in Figure 1 are those fences. The aliens , , , , sit inside a fence and belong to the Q region, while , , , , sit outside and belong to the W region.

Figure 1. Three dotted red fences separate the Q region from the W region.
There are very many ways to set up the fences. When you build them, it is better to put hydrophilic aliens in the W region and hydrophobic aliens in the Q region. You also want the sum of over the neighbour pairs with and to be as small as possible. Here means that alien is assigned to the Q region. Every alien belongs to exactly one of Q and W.
The objective function of this separation problem is the following.
The sum in runs over every pair joined by a grid edge.
Write a program that computes from the hydrophilic degrees of the aliens on the grid points.
Input
Your program reads from standard input. The first line holds the number of test cases . The first line of each test case holds the grid size (). The next lines hold the hydrophilic degree of the alien living at grid position as an matrix. Every is a real number with and exactly two digits after the decimal point.
Output
Your program writes to standard output. Print exactly one line for each test case. The line holds the real number with two digits after the decimal point.