CF101532H Corrupted Images(暴力模拟)
题面:
Husam has a lot of free time, so he is using this time in repairing corrupted binary images.
A Binary image can be represented as 2-dimensional array consisting of n rows, each of which is divided into m columns. The rows are numbered from 1 to n from top to bottom, and the columns are numbered from 1 to m from left to right. Each cell is identified by a pair (x, y), which means that the cell is located at row x and column y. The possible values in the binary images are either zero or one.
A binary image is good if all cells in the first row, last row, first column, and last column are ones. Otherwise, the binary image is corrupted. If the binary image is corrupted, Husam will fix it.
Husam wants to fix the image with the minimum number of moves, such that in each move he can swap the values at two different cells.
Can you help Husam by calculating the minimum number of required moves to fix the image?
Input:
The first line contains an integer T, where T is the number of test cases.
The first line of each test case contains two integers n and m (3 ≤ n, m ≤ 50), where n is the number of rows in the binary image, and m is the number of columns in each row.
Then n lines follow, each line contains m characters, giving the binary image. All values in the binary image are either zero or one.
Output:
For each test case, print a single line containing -1 if Husam cannot fix the binary image. Otherwise, print the minimum number of required moves to fix the image.
Example:
Note:
In the first test case, the image is good. In the second test case, Husam needs to swap the values of cells (2, 1) and (2, 2), and swap the values of cells (2, 3) and (3, 4), in order to fix the image.
分析:
题面可以把人脑壳读昏,我读得各种迷,是直到看了别人关于题面的解释才意识到其实很简单的。因为交换位置可以随意交换,所以其实题意就是,矩阵外围一圈这四条边上必须都是1,所以从内部的小方形里取1来和外围的0交换,只要外围的0少于等于内部的1,就可以交换成功,结果是外围1的个数,反之就没法交换成功,输出-1。
AC代码:
#include<cstdio>
#include<iostream>
using namespace std;
int t, n, m;
char num[55][55];
int zero, one;
int main(){
cin>>t;
while(t--){
cin>>n>>m;
zero = one = 0;
for(int i = 0; i < n; i++)
scanf("%s", &num[i]);
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(i > 0 && i < n-1 && j > 0 && j < m-1){
if(num[i][j] == '1') one++;
}
else{
if(num[i][j] == '0') zero++;
}
}
}
if(zero > one) cout<<-1<<endl;
else cout<<zero<<endl;
}
return 0;
}