题目链接
题意:
给你一个01矩阵,每次操作选择一个格子,使得该格子与上下左右四个格子的值翻转。 至少多少次操作可以使得矩阵中所有的值变为0?
请输出翻转方案,若没有方案,输出"IMPOSSIBLE”。
若有多种方案符合题意,请首先输出翻转次数最少的方案;若方案个数仍不唯一,则输出字典序最小的方案。
题目分析:
分析题目如果单纯爆搜的话O(2^N*M)肯定会超时,这里我们想到一些优化
首先改变前一行的1只有对下一行的同一列位置进行操作,我们由此想到,前一行的状态如果固定的话,下一行的状态也就固定的,我们可以枚举第一行的操作状态 ,并由这个状态先对第一行操作,然后依次对下一行进行操作,验证这个状态正确的情况是,当我们在最后一行为了满足前一行全是0进行操作结束后,最后一行恰好全是0,因为我们每步都是保证前一行是全0的。
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
#define x first
#define y second
#define fi first
#define se second
#define pb push_back
#define pf push_front
#define PI acos(-1)
#define fast ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int>PII;
typedef pair<double,double>PDD;
typedef pair<PII,int>PIII;
typedef set<int>::iterator SIT;
int gcd(int a,int b) {return b?gcd(b,a%b):a;}
int lcm(int a,int b) {return a/gcd(a,b)*b;}
const double eps=1e-6;
const int INF=0x3f3f3f3f,mod=1e9+7;
const int N=50;
int n,m;
int g[N][N];
int t[N][N],cur[N][N];
int step;
int ans[N][N];
void work(int x,int y){
cur[x][y]^=1;
cur[x][y-1]^=1;
cur[x][y+1]^=1;
cur[x+1][y]^=1;
}
bool solve(){
memcpy(cur,g,sizeof(g));
for(int j=1;j<=m;j++){//先由我们的状态更新第一行的数字
if(t[1][j]){
work(1,j);
step++;
}
}
for(int i=2;i<=n;i++){//然后依次依据前一行对每行进行更新
for(int j=1;j<=m;j++){
if(cur[i-1][j]){
t[i][j]=1;
work(i,j);
step++;
}
}
}
for(int j=1;j<=m;j++){//通过判断最后一行验证此状态的正确性
if(cur[n][j]) return false;
}
return true;
}
signed main(){
cin>>n>>m;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
cin>>g[i][j];
int min_step=INF;
for(int i=0;i<(1<<n);i++){
memset(t,0,sizeof(t));//每一个状态的初始化
step=0;
for(int j=0;j<m;j++){
t[1][j+1]=i>>j&1;//按字典序枚举所有状态
}
if(solve()&&step&&min_step>step){//更新答案
min_step=min(min_step,step);
memcpy(ans,t,sizeof(t));
}
}
if(min_step==INF){
cout<<"IMPOSSIBLE"<<endl;
}
else{
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++)
cout<<ans[i][j]<<' ';
cout<<endl;
}
}
return 0;
}
借鉴于https://blog.csdn.net/a1097304791/article/details/82997059