2021-03-20个人赛补题H - Corrupted Images

Posted 如风如影�

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2021-03-20个人赛补题H - Corrupted Images相关的知识,希望对你有一定的参考价值。

H - Corrupted Images

题目链接: link.
题目描述:
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?
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.
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.
样例

输入
3
3 3
111
101
111
4 4
1111
0111
1000
1111
4 5
10101
01010
10101
01010
输出
0
2
-1

题目大意:第一行,第一列,最后一行,最后一列都要用其余行列的元素修改为1,判断需要修改几次,若不能满足条件则输出-1.

这个题我在比赛做的时候想复杂了,拿过题一看,我首先想到的是bfs ,但仔细一想,其实挺简单,把外围,内部分别遍历一下,只要内部的1比外围的0多,即能满足条件。

代码如下(示例):

#include <bits/stdc++.h>
using namespace std;
char a[55][55];
int main() 
    int t;
    cin >> t;
    while (t--) 
        int n, m;
        cin >> n >> m;
       for(int i=0;i<n;i++)
         scanf("%s",&a[i]);
        int z = 0, y = 0;
        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 (a[i][j] == '1') y++;
                 
                else 
                    if (a[i][j] == '0') z++;
                
            
        
        if (y >= z)
            cout << z << endl;
        else
            cout << -1 << endl;
    
    return 0;


以上是关于2021-03-20个人赛补题H - Corrupted Images的主要内容,如果未能解决你的问题,请参考以下文章

2020.10.9个人赛补题

2020.5.10 个人rating赛 解题+补题报告

2020.5.10 个人rating赛 解题+补题报告

2020.4.19 个人rating赛 解题+补题报告

2020.4.12 个人rating赛 解题+补题报告

2021/11/21 ICPC沈阳站个人题解B,E,F,J(附赛时记录,另附赛后补题代码I,M)