我是BFS加位运算过的。提前求出了16种flip的异或值。
1753 | Accepted | 716K | 32MS | G++ | 1995B |
/*
ID: thestor1
LANG: C++
TASK: poj1753
*/
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <limits>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <cassert>
using namespace std;
void printBoard(int x)
{
cout << x << endl;
int k = 15;
for (int r = 0; r < 4; ++r)
{
for (int c = 0; c < 4; ++c)
{
// cout << "[debug]" << (x & (1 << k)) << endl;
if ((x & (1 << k)))
{
cout << 'b';
}
else
{
cout << 'w';
}
k--;
}
cout << endl;
}
cout << endl;
}
int main()
{
std::ios::sync_with_stdio(false);
std::vector<bool> visited(65536, false);
string line;
int cur = 0x0;
int k = 15;
for (int i = 0; i < 4; ++i)
{
cin >> line;
for (int j = 0; j < 4; ++j)
{
if(line[j] == 'b')
{
cur |= (1 << k);
}
k--;
}
}
// cout << "[debug]initial:" << endl;
// printBoard(cur);
int step = 0;
queue<int> que;
visited[cur] = true;
que.push(cur);
bool found = false;
int flips[] = {0xc800, 0xe400, 0x7200, 0x3100,
0x8c80, 0x4e40, 0x2720, 0x1310,
0x08c8, 0x04e4, 0x0272, 0x0131,
0x008c, 0x004e, 0x0027, 0x0013
};
while (!que.empty())
{
int qsize = que.size();
for (int i = 0; i < qsize; ++i)
{
cur = que.front();
que.pop();
if (cur == 0x0000 || cur == 0xffff)
{
found = true;
break;
}
// cout << "cur:" << endl;
// printBoard(cur);
for (int j = 0; j < 16; ++j)
{
int next = cur ^ flips[j];
// cout << "next:" << endl;
// printBoard(next);
if (!visited[next])
{
visited[next] = true;
que.push(next);
}
}
}
if (found)
{
break;
}
step++;
}
if (found)
{
cout << step << endl;
}
else
{
cout << "Impossible" << endl;
}
return 0;
}