Thinking: Use map<int,int> to record the states. Use a integer created by certain rules to represent states. After solving talked above, just combine them with bfs.
reference: https://github.com/morris821028/UVa/blob/master/volume111/11198%20-%20Dancing%20Digits.cpp
AC code:
#include<iostream>
#include<cstring>
#include<cmath>
#include<map>
#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#define MAX(a,b) ((a)>(b)?(a):(b))
#define MIN(a,b) ((a)<(b)?(a):(b))
using namespace std;
bool prime[20];
bool candance[10][10];
int main()
{
memset(prime, true, sizeof(prime));
int sequence[8], sign[9];
int T = 0;
for (int i = 2; i < 20; i++)
for (int j = i*i; j < 20; j += i)
{
prime[j] = false;
}
for (int i = 1; i <= 8; i++)
for (int j = 1; j <= 8; j++)
candance[i][j] = prime[i + j];
while (scanf("%d", &sequence[0])!=EOF)
{
T++;
if (sequence[0] == 0)
break;
if (sequence[0] < 0)
{
sequence[0] *= -1;
sign[sequence[0]] = 1;
}
else sign[sequence[0]] = 0;
int HASH = sequence[0];//TO SAVE THE STATE
for (int i = 1; i < 8; i++)
{
scanf("%d", &sequence[i]);
if (sequence[i] < 0)
{
sequence[i] *= -1;
sign[sequence[i]] = 1;
}
else sign[sequence[i]] = 0;
HASH = HASH * 10 + sequence[i];
}
queue<int> Q;
map<int, int> state;
Q.push(HASH);
state[HASH] = 0;
int temp[8], temp_hash,step;
while (!Q.empty())
{
temp_hash = Q.front();
Q.pop();
step = state[temp_hash];
if (temp_hash == 12345678)
{
temp_hash = -1;
break;
}
for (int i = 7; i >= 0; i--)
{
temp[i] = temp_hash % 10;
temp_hash /= 10;
}
for (int i = 0; i < 8; i++)// i try to dance with j
for (int j = 0; j < 8; j++)
{
if (i == j)
continue;
if (sign[temp[i]] != sign[temp[j]] && candance[temp[i]][temp[j]])
{
// i tries to go to j's left
int k = 0;
int now_hash = 0;
for (; k < j; k++)
{
if (k == i)
continue;
now_hash = now_hash * 10 + temp[k];
}
now_hash = now_hash * 10 + temp[i];
now_hash = now_hash * 10 + temp[j];
for (k = j + 1; k < 8; k++)
{
if (k == i)
continue;
now_hash = now_hash * 10 + temp[k];
}
if (state.find(now_hash) == state.end())
{
state[now_hash] =step+ 1;
Q.push(now_hash);
}
// i tries to go to j's right
for (k = 0, now_hash = 0; k < j; k++)
{
if (k == i)
continue;
now_hash = now_hash * 10 + temp[k];
}
now_hash = now_hash * 10 + temp[j];
now_hash = now_hash * 10 + temp[i];
for (k = j + 1; k < 8; k++)
{
if (k == i)
continue;
now_hash = now_hash * 10 + temp[k];
}
if (state.find(now_hash) == state.end())
{
state[now_hash] = step + 1;
Q.push(now_hash);
}
}
}
}
printf("Case %d: ", T);
if (temp_hash == -1)
printf("%d\n", state[12345678]);
else printf("-1\n");
}
return 0;
}