#include <stdio.h>
#include <string.h>
#include <conio.h>
#define N 5040
struct statt
{
int step;
int zero; //0的位置
char str[9];
}start, cur, tmp, q[N];
int mov[7][5] = {{3, 2, 4, 6},{2, 2, 6}, {3, 0, 1, 3},
{2, 2, 4}, {3, 0, 3, 5}, {2, 4, 6}, {3, 0, 1, 5}};
char seq[9];
char goal[] = "0123456";
int mark[6543211];
void swp(int a, int b)
{
int t = tmp.str[a];
tmp.str[a] = tmp.str[b];
tmp.str[b] = t;
}
int to_num(char *q)
{
int i, ret=0;
for(i=0; i<7; i++)
{
ret = ret * 10 + q[i] - '0';
}
return ret;
}
void bfs()
{
int m, i;
int front = 0, rear = 0;
q[front++] = start;
while(rear < front)
{
cur = q[rear];
rear = (rear + 1) % N;
for(i=1; i<=mov[cur.zero][0]; i++)
{
strcpy(tmp.str, cur.str);
swp(cur.zero, mov[cur.zero][i]);
m = to_num(tmp.str);
if(mark[m] < 0)
{
mark[m] = cur.step+1 ; //状态需要几步到达
tmp.step = cur.step + 1;
tmp.zero = mov[cur.zero][i];
q[front] = tmp;
front = (front + 1) % N;
}
}
}
}
int main()
{
int t, m;
freopen("3221.in", "r",stdin);
freopen("3221.out", "w",stdout);
memset(mark, -1, sizeof(mark));
/*预处理*/
m = to_num(goal);
start.step = 0;
start.zero = 0;
strcpy(start.str, goal);
mark[m] = 0;
bfs();
scanf("%d", &t);
while(t--)
{
scanf("%d", &m);
printf("%d\n", mark[m]);
}
getch();
return 0;
}
|