POJ 1753 Flip Game
传送门
题意:有一个4*4的棋盘,上面铺满了黑白棋子,问最少改变几次能使棋盘全黑或者全白。改变棋子的规则是棋子本身改变,同时它上下左右的棋子状态改变,即0变1,1变0。
思路:翻了几次容易发现,某个棋子翻偶数次的状态和不翻是一样的,翻奇数次的状态和值翻了1次是一样的,所以对于某个棋子来说,无论翻多少次要么和翻0次一样要么和翻1次一样。所以问题就变成了某个棋子要么翻要么不翻。
总共就有
种情况,两个想法。
一打张表,在一一枚举找答案,这个比较好想,写起来麻烦,而且时间效率不高。
二就是在目前状态下枚举,效率高了点,而且好写。
还有这道题只有01,可以状态压缩,这里不讲。
位运算也可以过。
不过不会高斯消元解法……
代码是第二种想法的
如下:
#include<cstdio>
int g[4][4],ans=233,tot;
char c;
void change(int x,int y)//变换
{
g[x][y]=!g[x][y];
if(x>0)g[x-1][y]=!g[x-1][y];
if(x<3)g[x+1][y]=!g[x+1][y];
if(y>0)g[x][y-1]=!g[x][y-1];
if(y<3)g[x][y+1]=!g[x][y+1];
}
int check()//检查是否符合
{
int tot=0;
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
tot+=g[i][j];
if(!tot||tot==16)return 1;
return 0;
}
void dfs(int x,int y,int i)
{
if(i==16)return;
for(int j=0;j<2;j++)
{
int u=g[x][y];
if(u!=j)change(x,y),tot++;//判断是不是改变了
if(check()&&tot<ans)ans=tot;//更新答案
dfs((x+1)%4,x+1==4?y+1:y,i+1);//找下一个点
if(u!=j)change(x,y),tot--;//还原
}
}
int main()
{
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
scanf("%c",&c);
if(c=='b')
g[i][j]=1;
}
scanf("%*c");
}
dfs(0,0,0);
if(ans==233)puts("Impossible");
else printf("%d\n",ans);
return 0;
}