http://poj.org/problem?id=1753
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 39180 | Accepted: 17033 |
Description
- Choose any one of the 16 pieces.
- Flip the chosen piece and also all adjacent pieces to the
left, to the right, to the top, and to the bottom of the chosen piece
(if there are any).
Consider the following position as an example:
bwbw
wwww
bbwb
bwwb
Here "b" denotes pieces lying their black side up and "w" denotes
pieces lying their white side up. If we choose to flip the 1st piece
from the 3rd row (this choice is shown at the picture), then the field
will become:
bwbw
bwww
wwwb
wwwb
The goal of the game is to flip either all pieces white side up or
all pieces black side up. You are to write a program that will search
for the minimum number of rounds needed to achieve this goal.
Input
Output
to the output file a single integer number - the minimum number of
rounds needed to achieve the goal of the game from the given position.
If the goal is initially achieved, then write 0. If it's impossible to
achieve the goal, then write the word "Impossible" (without quotes).
Sample Input
bwwb
bbwb
bwwb
bwww
Sample Output
4
思路:
1.首先需要理解一点,每个位置最多翻一次,翻两次等于没有翻,而且,最终结果只与翻的位置有关,与翻的次序无关。故而,最多翻16次,若翻了16次还没有达到目的,那就无解。
2.求最少步数,则bfs,效率最高。
3.采取位运算压缩状态,把16个位置的状态用bit存储,即16位,每次翻转后的状态存入que队列。
4.优化:16步长检查;相同状态值检查。
程序:
#include <iostream>
#include <fstream>
using namespace std; #define n 16
#define N (1 << 16) struct Node
{
int count;
bool b;
}node[N];
int value;
int que[N + ]; void Init ()
{
char c;
while (~scanf("%c", &c))
{
if (c == 'b')
{
value <<= ;
value |= ;
}
else if (c == 'w')
{
value <<= ;
}
}
}
inline bool Check (int i, int j)
{
return i >= && i < && j >= && j < ;
}
void Bfs ()
{
int front = , rear = , ans = n;
if (value == || value == 0x0ffff)
{
puts("");
return;
}
memset(node, , (sizeof(node) << ));
que[] = value;
node[value].b = true;
while (front != rear)
{
int tmp = que[front++];
int ttmp;
if (node[tmp].count == n)
{
break;
}
for (int i = ; i < ; i++)
{
for (int j = ; j < ; j++)
{
ttmp = tmp;
int tttmp = (i << ) + j;
ttmp ^= ( << tttmp);
if (Check(i - , j))
{
ttmp ^= ( << (tttmp - ));
}
if (Check(i + , j))
{
ttmp ^= ( << (tttmp + ));
}
if (Check(i, j - ))
{
ttmp ^= ( << (tttmp - ));
}
if (Check(i, j + ))
{
ttmp ^= ( << (tttmp + ));
}
if (!node[ttmp].b)
{
node[ttmp].b = true;
node[ttmp].count = node[tmp].count + ;
que[rear++] = ttmp;
}
if (ttmp == || ttmp == 0x0ffff)
{
printf("%d\n", node[ttmp].count);
return;
}
}
}
}
puts("Impossible");
} int main ()
{
//freopen("D:\\input.in","r",stdin);
Init();
Bfs();
return ;
}