bfs poj2965

TLE了 不知道怎么办 还是用枚举?

// poj 2965  bfs & STL queue
# include <iostream>
# include <cstring>
# include <queue>

using namespace std;

const unsigned short flip[] = {0x111f, 0x222f, 0x444f, 0x888f,
0x11f1, 0x22f2, 0x44f4, 0x88f8,
0x1f11, 0x2f22, 0x4f44, 0x8f88,
0xf111, 0xf222, 0xf444, 0xf888};

unsigned short bfs(unsigned short start);
bool judge(unsigned short start, unsigned short x);

int main()
{
char board[4][4];
for (int i=0; i<4; ++i)
cin >> board[i];
unsigned short start = 0x0;
for (int i=0; i<4; ++i)
for (int j=0; j<4; ++j)
if (board[i][j]=='+')
start += 1<<(i*4+j);
unsigned short ans;
ans = bfs(start);
if (ans == 0) cout << 0 << endl;
else
{
int cnt = 0;
for (int i=0; i<16; ++i)
if (ans>>i & 0x1) ++cnt;
cout << cnt << endl;
for (int i=0; i<16; ++i)
if (ans>>i & 0x1)
cout << i/4+1 << ' ' << i%4+1 << endl;
}
return 0;
}
unsigned short bfs(unsigned short start)
{
queue<unsigned short> Q;
bool vis[1<<16];
memset(vis, 0, sizeof(vis));
Q.push(0);
while (!Q.empty())
{
unsigned short x;
x = Q.front();
Q.pop();
vis[x] = true;
if (judge(start, x))return x;
for (int i=0; i<16; ++i)
{
if ((x>>i) & 0x1) ;
else if (!vis[x+(1<<i)])
Q.push(x+(1<<i));
}
}
return 0;
}
bool judge(unsigned short start, unsigned short x)
{
for (int i=0; i<16; ++i)
if (x>>i & 0x1) start ^= flip[i];
if(start == 0) return true;
else return false;
}

posted on 2012-02-16 00:07  getgoing  阅读(204)  评论(0编辑  收藏  举报

导航