#P1173. [NOI2016] 网格
[NOI2016] 网格
Description
The Flea King and the Cricket King are playing a game.
They deploy pieces on an -row, -column grid. Among the cells (), each such cell contains a cricket, and each remaining cell contains a flea.
Two fleas are called adjacent if their occupied cells share a side.
Two fleas are called connected if and only if they are adjacent, or there exists a sequence of fleas starting from one and ending at the other such that consecutive fleas in the sequence are adjacent.
Now, the Cricket King wants to replace some fleas (zero, one, or more) with crickets so that afterwards there exist at least two fleas that are not connected.
For example: Figure describes a case with , , .

In this case, the Cricket King can replace the fleas at row , column and row , column with crickets to achieve his goal, as shown in the right picture. Moreover, no better plan exists, although there may be other plans that also replace two fleas.
You must first determine whether the Cricket King's goal can be achieved. If it can, you must also minimize the number of fleas replaced.
Input Format
Each input file contains multiple test cases.
The first line contains a single integer , the number of test cases.
For each of the next test cases, the first line contains three integers .
Then lines follow. Each line contains two integers indicating that the cell in row , column is occupied by a cricket. Within each test case, no cricket cell is listed more than once.
Output Format
For each test case, output one line.
If the Cricket King's goal cannot be achieved for this test case, output . Otherwise, output the minimum number of fleas that must be replaced.
4
4 4 2
1 1
4 4
2 3 1
1 2
2 2 2
1 1
2 2
1 1 0
2
1
0
-1
Hint
Sample explanation
- The first test case is the example in the statement.
- For the second test case, replacing the flea at row , column makes two fleas not connected, and no better plan exists.
- For the third test case, there already exist two fleas that are not connected initially, so no replacements are needed.
- For the fourth test case, since there is at most one flea, no matter how you replace, there cannot exist two fleas that are not connected.
Constraints
For all test points, it is guaranteed that . Let denote, within one test point, the sum of over its test cases. For all test points, .
For all data, , , , .
The detailed constraints for each test point are shown in the table below. In the table, refer to a single test case (not a test point), i.e., all test cases within the same test point meet the listed limits; and is for a single test point. For readability, the “Test Point” column is placed in the middle rather than on the left.
| Test Point | ||
|---|---|---|
| ^ | ||
| ^ | ||
| ^ | ||
| ^ | ||
Translated by ChatGPT 5
京公网安备 11011102002149号