分析:
一:每个位置最多只会被点击一次。
二:固定第一行,方案最多只有一种。因为固定了前 i 行,若第 i 行中出现了 0,则只能通过点击第 i+1 行来修改第 i 行中的 0。
三:点击的先后顺序不影响结果。
所以枚举出第一行所有的点击情况(每一个位置点或不点共2^5种),并将第一行固定下来,然后从第二行开始往后地推即可。
#include <bits/stdc++.h>
#define IOS ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define _zero(a) memset(a, 0, sizeof(a))
#define endl '\n'
#define int long long
#define mp make_pair
#define x first
#define y second
#define all(a) (a).begin(), (a).end()
#define rall(a) (a).rbegin(), (a).rend()
typedef long long ll;
typedef double dd;
typedef long double ld;
using namespace std;
const int inf = 1e10;
const int M = 998244353;
const ld pi = atan2(0, -1);//arctan(y/x);
const ld eps = 1e-4;
int idx[4] = {1, 0, -1, 0}, idy[4] = {0, -1, 0, 1};
string s[5];
int numsall[7][7], nums[7][7];
void getnums()
{
for(int i = 0; i < 5; i++)
for(int j = 0; j < 5; j++)
nums[i][j] = numsall[i][j];
}
void click(int a, int b)
{
nums[a][b] ^= 1;
for(int i = 0; i < 4; i++){
int nx = a + idx[i], ny = b + idy[i];
if(nx >= 0 && nx < 5 && ny >= 0 && ny < 5) nums[nx][ny] ^= 1;
}
}
int solve(int bit)
{
getnums();
int cnt = 0;
for(int i = 0; i < 5; i++){
if(bit >> i & 1){
click(0, i);
++cnt;
}
}
for(int i = 1; i < 5; i++){
for(int j = 0; j < 5; j++){
if(nums[i-1][j] == 0){
++cnt;
click(i, j);
if(cnt > 6) return inf;
}
}
}
for(int i = 0; i < 5; i++) if(nums[4][i] == 0) return inf;
return cnt;
}
signed main()
{
IOS;
int tt;
cin >> tt;
while(tt--){
for(int i = 0; i < 5; i++) cin >> s[i];
for(int i = 0; i < 5; i++)
for(int j = 0; j < 5; j++)
numsall[i][j] = s[i][j] - '0';
int ans = inf;
for(int bit = 0; bit < 1 << 5; bit++){
ans = min(ans, solve(bit));
}
if(ans == inf) cout << "-1" << endl;
else cout << ans << endl;
}
return 0;
}
《算法竞赛进阶指南习题》