您的位置:首页 > 其它

poj 1753 Flip Game

2011-01-13 14:27 288 查看
第一次写状态压缩bfs,这是个学状态压缩的好题。

每个棋子最多改变一次,如果变两次那么又变回去了。把每个棋子看成是一个16位二进制数的一位,如果是白色,那么对应位就位1,这样就对应了,2^16-1种状态。

/*
* File:   main.cpp
* Author: mi
*
* Created on 2011年1月13日, 下午1:59
*/
#include <cstdlib>
#include <stdio.h>
#include <string.h>
#include <queue>
#define BLACK 0
#define WRITE ((1<<16)-1)
using namespace std;
/*
*
*/
struct node
{
int cnt,mode;
}p,pp;
int used[(1<<16)-1]={0};
void change(int x,int y)
{
pp.mode^=1<<(4*x+y);
if(x==0)
{
pp.mode^=1<<(y+4);
}
else if(x==3)
pp.mode^=1<<(y+8);
else
{
pp.mode^=1<<(4*(x-1)+y);
pp.mode^=1<<(4*(x+1)+y);
}
if(y==0)
pp.mode^=1<<(4*x+1);
else if(y==3)
pp.mode^=1<<(4*x+2);
else
{
pp.mode^=1<<(4*x+y-1);
pp.mode^=1<<(4*x+y+1);
}
}
void bfs()
{
int i,j;
queue<node> q;
while(!q.empty())
q.pop();
q.push(p);
while(!q.empty())
{
node temp=q.front();
q.pop();
temp.cnt++;
for(i=0;i<4;i++)
for(j=0;j<4;j++)
{
pp=temp;
change(i,j);
if(pp.mode==BLACK||pp.mode==WRITE)
{
printf("%d/n",pp.cnt);
return ;
}
if(!used[pp.mode])
{
used[pp.mode]=1;
q.push(pp);
}
}
}
puts("Impossible");
}
int main(int argc, char** argv)
{
int i,j,cnt=0;
char s;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++,cnt++)
{
scanf("%c",&s);
if(s=='w')
p.mode+=(1<<cnt);
}
getchar();
}
if(p.mode==BLACK||p.mode==WRITE)
puts("0");
else
{
used[p.mode]=1;
bfs();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: