B - Fliptile
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× 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".
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
4 4 1 0 0 1 0 1 1 0 0 1 1 0 1 0 0 1
0 0 0 0 1 0 0 1 1 0 0 1 0 0 0 0
#include<string.h>
int g[16][16]; //格子
int ans[16][16]; //答案翻转次数
int state[16][16]; //记录当前状态下的翻转状态
int next[5][2]={{1,0},{-1,0},{0,0},{0,1},{0,-1}};
int m,n,max=0x3f3f3f3f;
int check(int x,int y)
{
int i;
int num=g[x][y];//别忘了加上自己的状态
for(i=0;i<5;i++){
int tx=x+next[i][0];
int ty=y+next[i][1];
if(tx<0||ty<0||tx>=m||ty>=n)
continue;
num=num+state[tx][ty];
}
return num%2; //若需要翻转偶数次,则相当于不翻转,奇数次相当于翻转一次
}
int flip()
{
int i,j;
for(i=1;i<m;i++)
for(j=0;j<n;j++)
if(check(i-1,j)) //如果第i-1行的j位置为1,则必翻转i,j格子(由上一个格子决定该格子是否翻转)
state[i][j]=1; //翻转一次
for(i=0;i<n;i++) //检查最后一行是否全为0
if(check(m-1,i)!=0)
return -1;
int ans=0; //当前状态的翻转步数
for(i=0;i<m;i++)
for(j=0;j<n;j++)
ans=ans+state[i][j];
return ans;
}
int main()
{
int i,j,k;
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&g[i][j]);
int cnt=max;
for(i=0;i<(1<<n);i++) //从n个0到n个1枚举,(将1左移n位)
{
memset(state,0,sizeof(state));
for(j=0;j<n;j++)
state[0][n-j-1]=((i>>j)&1); //将i(第一行的状态)向右移0~j位,检测出每一位的状态
int temp=flip();
if(temp>0&&cnt>temp)
{
cnt=temp;
for (int i = 0; i < 20; i++)
for (int j = 0; j < 20; j++)
ans[i][j] = state[i][j];
}
}
if(cnt==max)
printf("IMPOSSIBLE"); //第一行2的n次方种状态均不能全部翻转成0
else
for (i=0;i<m; i++)
for (j=0;j<n;j++)
if (j== n-1)
printf("%d\n", ans[i][j]);
else
printf("%d ", ans[i][j]);
return 0;
}