Description
Farmer John knows that an intellectually satisfied cow is a happy cow who will give more milk. He has arranged a brainy activity for cows in which they manipulate an M x N grid (1 <= M <= 15; 1 <= N <= 15) of square tiles, each of which is colored black on one side and white on the other side. As one would guess, when a single white tile is flipped, it changes to black; when a single black tile is flipped, it changes to white. The cows are rewarded when they flip the tiles so that each tile has the white side face up. However, the cows have rather large hooves and when they try to flip a certain tile, they also flip all the adjacent tiles (tiles that share a full edge with the flipped tile). Since the flips are tiring, the cows want to minimize the number of flips they have to make. Help the cows determine the minimum number of flips required, and the locations to flip to achieve that minimum. If there are multiple ways to achieve the task with the minimum amount of flips, return the one with the least lexicographical ordering in the output when considered as a string. If the task is impossible, print one line with the word "IMPOSSIBLE".
Input
* Line 1: Two space-separated integers: M and N
* Lines 2..M+1: Line i+1 describes the colors (left to right) of row i of the grid with N space-separated integers which are 1 for black and 0 for white
Output
* Lines 1..M: Each line contains N space-separated integers, each specifying how many times to flip that particular location.
这个题艾教很早很早之前就讲过,现在才是第一遍全靠自己理解实现。
很容易想到,如果第一行状态确定了,我们就可以知道第二行,哪些点选或不选了,如果上面是黑色的,那么肯定下面要按,不然就没有机会了。所以我们可以先用2^15枚举第一行每个点转或不转,后面跟着推下来就好了。总复杂度15*2^15是不超的。
至于字典序最小的问题,由于我们在枚举第一行的状态时,0,1就肯定不一样了,所以从小到大枚举状态,遇到解了直接输出即可。
下附AC代码。
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define maxn 16
using namespace std;
int n,m;
int flag;
int a[maxn][maxn],now[maxn][maxn],pre[maxn][maxn];
int fx[10]={0,1,-1,0,0};
int fy[10]={0,0,0,1,-1};
int check()
{
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
if(now[i][j])
return false;
return true;
}
void expa(int x,int y)
{
pre[x][y]=1;
now[x][y]^=1;
for(int k=1;k<=4;k++)
{
int nx=x+fx[k],ny=y+fy[k];
if(1<=nx && nx<=n && 1<=ny && ny<=m)
now[nx][ny]^=1;
}
}
void dfs(int line)
{
if(line==n+1)
{
if(check())
flag=1;
return;
}
for(int i=1;i<=m;i++)
if(now[line-1][i]==1)
{
expa(line,i);
}
dfs(line+1);
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
scanf("%d",&a[i][j]);
for(int state=0;state<(1<<n);state++)
{
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
now[i][j]=a[i][j];
memset(pre,0,sizeof(pre));
for(int i=1;i<=m;i++)
{
if(state&(1<<(i-1)))
{
expa(1,i);
}
}
dfs(2);
if(flag)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<m;j++)
{
printf("%d ",pre[i][j]);
}
printf("%d",pre[i][m]);
printf("\n");
}
return 0;
}
}
printf("IMPOSSIBLE\n");
return 0;
}