原题链接:
题目描述:
You are given a matrix consisting of nn rows and mm columns. Each cell of this matrix contains 0 or 1.
Let's call a square of size 2×2 without one corner cell an L-shape figure. In one operation you can take one L-shape figure, with at least one cell containing 1 and replace all numbers in it with zeroes.
Find the maximum number of operations that you can do with the given matrix.
题目大意:
题目给定一个n行m列且仅有1和0组成的矩阵,我们每次操作选择一个2*2的L型块,要求这个L块至少得有1个1,然后将这个L块全部清0。请问我们最多能操作多少次。
解题思路:
很显然我们可以每次都找到1最少的那个L块进行操作,每次尽量清理尽可能少的1,但如果真的就这样模拟的话不仅麻烦而且会TLE(大概吧,我也没试过,emmm),我们在纸上模拟模拟就会发现:
如果一开始1最少的那个L块1的个数为1那么答案就是整个矩阵1的个数(每次操作都只删除一个1);
如果一开始1最少的那个L块1的个数为3(即整个矩阵都是1),那么我们第一次操作的时候会砍掉3个1,从此之后我们每次操作都可以只清理1个1,所以我们最多可以操作sum-2次(sum为整个矩阵1的个数);
如果一开始1最少的那个L块1的个数为2,那么我们第一次操作的时候会砍掉两个1,从此之后我们每次操作也是都可以只清理1个1,所以我们最多可以操作sum-1次。
整个矩阵全都是0,则可以直接特判输出0。
具体实现的时候,可以专门写一个函数来计算当前2*2矩阵中的所有L块的最少1。枚举所有的2*2矩阵,即可计算出整个矩阵1最少的L块。
代码(CPP):
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 1e3 + 10;
const int INF = 0x3fffffff;
int n, m, a[maxn][maxn];
// 计算以(i,j)为左上角顶点的2*2矩阵中所有L块中最少的1的个数
int calc(int i, int j)
{
int Min = min(a[i][j] + a[i + 1][j] + a[i + 1][j + 1], a[i][j] + a[i][j + 1] + a[i + 1][j + 1]);
Min = min(Min, a[i][j + 1] + a[i + 1][j + 1] + a[i + 1][j]);
Min = min(Min, a[i][j + 1] + a[i][j] + a[i + 1][j]);
return Min;
}
int main()
{
freopen("in.txt", "r", stdin);
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cout << fixed;
cout.precision(18);
int t;
cin >> t;
while(t--)
{
cin >> n >> m;
int sum = 0;
for (int i = 1; i <= n; i++)
{
string s;
cin >> s;
s = " " + s;
for (int j = 1; j <= m; j++)
{
a[i][j] = s[j] - '0';
if(a[i][j] == 1)
sum++;
}
}
if(sum == 0)
{
cout << "0\n";
continue;
}
if(sum == n * m)
{
cout << sum - 2 << "\n";
continue;
}
int Min = INF;
for (int i = 1; i <= n - 1; i++)
{
for (int j = 1; j <= m - 1; j++)
{
Min = min(Min, calc(i, j));
}
}
if(Min == 2)
sum--;
cout << sum << "\n";
}
return 0;
}