九数码

来源:互联网 发布:什么软件旅游便宜 编辑:程序博客网 时间:2024/04/29 15:25
Problem DescriptionNine tiles, each with a number from 1 to 9 on it, are packed into a 3 by 3 frame. Your task is to arrange the tiles so that they are ordered as 1 2 34 5 67 8 9At each step, you can do the following operation to the tiles: Choose 2 by tiles, rotate the tiles in clockwise order. For example:1 2 3-->4 1 34 5 6-->5 2 67 8 9-->7 8 9or1 2 3-->1 2 34 5 6-->4 8 57 8 9-->7 9 6Write a program to find the minimum number of steps.InputInput contains multiple test cases.each test case is a description of a configuration of the nine tiles. The description is just a list of the tiles in there initial positions, with the rows listed from top to bottom, and from left to right within a row, where the tiles are represented by numbers 1 to 9. For example:9 8 76 5 43 2 1is described by this list:9 8 7 6 5 4 3 2 1OutputOutput the minimum number of steps on a single line for each test case.Sample Input1 2 3 4 5 6 7 8 94 1 3 5 2 6 7 8 9Sample Output03//关键字:康拓展开//标程:<pre name="code" class="html">#include <iostream>#include <cstdio>#include <cstring>#include <queue>using namespace std;struct node{    char a[9];    int step;}q[370000];int  ans[370000];int c[8] = {1,2,6,24,120,720,5040,40320};int s[4][9]={{1,4,2,0,3,5,6,7,8},{0,2,5,3,1,4,6,7,8},{0,1,2,4,7,5,3,6,8},{0,1,2,3,5,8,6,4,7}};int kangtuo(node &tmp){    int ret = 0;    for(int i = 0; i < 8; ++ i)        for(int j = i+1; j < 9; ++ j)          if(tmp.a[i] > tmp.a[j]) ret += c[7-i];    return ret;}void fun(){    node tmp;    for(int i = 0; i < 9; ++ i) tmp.a[i] = '0'+i;    tmp.step = 0;    memset(ans,-1,sizeof(ans));    ans[kangtuo(tmp)] = 0;    int head = -1,last = 0;    q[0] = tmp;    while(head ++ < last)    {        tmp = q[head];        node tp;        tp.step = tmp.step + 1;        for(int i = 0; i < 4; ++ i)        {            for(int j = 0; j < 9; ++ j)                tp.a[j] = tmp.a[s[i][j]];            int k = kangtuo(tp);            if(ans[k] < 0)            {                ans[k] = tp.step;                q[++last] = tp;            }        }    }}int main(){//    freopen("a.txt","r",stdin);    fun();    int x;    while(scanf("%d",&x)!=EOF)    {        node tmp;        tmp.a[0] = x;        for(int i = 1; i < 9; ++ i)        {            scanf("%d",&x);            tmp.a[i] = x;        }        printf("%d\n",ans[kangtuo(tmp)]);    }    return 0;}

0 0