HDU 3567 Eight II 【bfs预处理】【八码问题】【康托展开】

Eight II

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 130000/65536 K (Java/Others)
Total Submission(s): 4477    Accepted Submission(s): 973


 

Problem Description

Eight-puzzle, which is also called "Nine grids", comes from an old game.

In this game, you are given a 3 by 3 board and 8 tiles. The tiles are numbered from 1 to 8 and each covers a grid. As you see, there is a blank grid which can be represented as an 'X'. Tiles in grids having a common edge with the blank grid can be moved into that blank grid. This operation leads to an exchange of 'X' with one tile.

We use the symbol 'r' to represent exchanging 'X' with the tile on its right side, and 'l' for the left side, 'u' for the one above it, 'd' for the one below it.



A state of the board can be represented by a string S using the rule showed below.



The problem is to operate an operation list of 'r', 'u', 'l', 'd' to turn the state of the board from state A to state B. You are required to find the result which meets the following constrains:
1. It is of minimum length among all possible solutions.
2. It is the lexicographically smallest one of all solutions of minimum length.

 

 

Input

The first line is T (T <= 200), which means the number of test cases of this problem.

The input of each test case consists of two lines with state A occupying the first line and state B on the second line.
It is guaranteed that there is an available solution from state A to B.

 

 

Output

For each test case two lines are expected.

The first line is in the format of "Case x: d", in which x is the case number counted from one, d is the minimum length of operation list you need to turn A to B.
S is the operation list meeting the constraints and it should be showed on the second line.

 

 

Sample Input

 

2 12X453786 12345678X 564178X23 7568X4123

 

 

Sample Output

 

Case 1: 2 dd Case 2: 8 urrulldr

 

 

Author

zhymaoiing

 

 

Source

2010 ACM-ICPC Multi-University Training Contest(13)——Host by UESTC

 

 

Recommend

zhouzeyong

 

 

这题我先按照上一题的A*做法做了一遍,结果超时了。

 

A*超时版本:

#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define LL long long
#define M(a,b) memset(a,b,sizeof(a))
const int MAXN = 4e5+5;
const int INF = 0x3f3f3f3f;
int T,Case=1;
int HASH[9] = {1,1,2,6,24,120,720,5040,40320};
int X[4] = {0,-1,1,0};
int Y[4] = {-1,0,0,1};
char op[4] = {'l','u','d','r'};
int str1[15];
int str2[15];
vectorv[9];
struct Node
{
    int x,y;
    int f,g,h;
    int hash_num;
    int num[3][3];
    bool operator<(const Node &k) const
    {
        return f>k.f;
    }
} st,ed;
int vis[MAXN];
priority_queueq;
struct Node2
{
    char c;
    int pre;
} Path[MAXN];
void init()
{
    M(vis,0);
    while(!q.empty()) q.pop();
    for(int i=0; i<9; i++) v[i].clear();
}
int get_hash(Node s)
{
    int num2[10];
    int len  = 0;
    for(int i=0; i<3; i++)
    {
        for(int j=0; j<3; j++)
        {
            num2[len++] =s.num[i][j];
        }
    }
    int ans = 0;
    int sum = 0;
    for(int i=0; i<9; i++)
    {
        sum = 0;
        for(int j=0; jnum2[i]) sum++;
        }
        ans+=(sum*HASH[i]);
    }
    return ans;
}
int get_manhadun(Node s)
{
    int sum = 0 ;
    for(int i=0; i<3; i++)
    {
        for(int j=0; j<3; j++)
        {
            if(s.num[i][j] !=0 )
            {
                sum+=(abs(i-v[s.num[i][j]][0]) + abs(j-v[s.num[i][j]][1]));
            }
        }
    }
    return sum ;
}
void ROUTE(int s)
{
    if(Path[s].pre==-1)
    {
        return ;
    }
    ROUTE(Path[s].pre);
    printf("%c",Path[s].c);
}
int A_star(Node s)
{
    s.g = 0;
    s.h = get_manhadun(s);
    s.f = s.g + s.h;
    vis[s.hash_num] = 1;
    Path[s.hash_num].pre = -1;

    q.push(s);
    while(!q.empty())
    {

        Node temp = q.top();
        q.pop();
        int x1 = temp.x;
        int y1 = temp.y;

        for(int i=0; i<4; i++)
        {
            int xx = x1 +X[i];
            int yy = y1 +Y[i];
            if(xx>=0&&xx<3&&yy>=0&&yy<3)
            {
                Node temp2 = temp;
                swap(temp2.num[x1][y1],temp2.num[xx][yy]);
                int thash_num = get_hash(temp2);
                if(vis[thash_num])continue;
                else vis[thash_num] = vis[temp.hash_num]+1;
//                printf("x1==%d y1==%d xx==%d yy==%d\n",x1,y1,xx,yy);
//                for(int i=0; i<3; i++)
//                {
//                    for(int j=0; j<3; j++)
//                    {
//                        printf("%d ",temp2.num[i][j]);
//                    }
//                    printf("\n");
//                }
//                printf("i==%d c==%c",i,op[i]);
//                printf("\n");
//                printf("\n");
                temp2.x =xx;
                temp2.y =yy;
                temp2.hash_num = thash_num ;
                temp2.g++;
                temp2.h = get_manhadun(temp2);
                temp2.f = temp2.f+temp2.g;
                q.push(temp2);
                Path[thash_num].pre = temp.hash_num;
                Path[thash_num].c = op[i];


                if(thash_num == ed.hash_num)
                {
                    printf("Case %d: %d\n",Case++,vis[thash_num]-1);
                    ROUTE(thash_num);
                    printf("\n");
                    return 1;
                }
            }
        }
    }
}
int main()
{
    cin>>T;
    while(T--)
    {
        init();
        for(int i=0; i<9; i++)
        {
            char temp;
            cin>>temp;
            if(temp == 'X')
            {
                st.x = i/3;
                st.y = i%3;
                st.num[i/3][i%3] = 0;
            }
            else
            {
                st.num[i/3][i%3] = temp-'0';
            }
        }

        st.hash_num = get_hash(st);
        for(int i=0; i<9; i++)
        {
            char temp;
            cin>>temp;
            if(temp == 'X')
            {
                ed.x = i/3;
                ed.y = i%3;
                ed.num[i/3][i%3] = 0;
                v[0].push_back(i/3);
                v[0].push_back(i%3);
            }
            else
            {
                ed.num[i/3][i%3] = temp-'0';
                v[temp-'0'].push_back(i/3);
                v[temp-'0'].push_back(i%3);
            }
        }
        ed.hash_num = get_hash(ed);
        if(st.hash_num==ed.hash_num)
        {
            printf("Case %d: %d\n",Case++,0);
            continue;
        }
        A_star(st);
    }
    return 0;
}

然后看了大神的博客,学到了这题需要预处理一下,从而节省大量时间。

 

首先我们枚举X所在的9个位置

比如

X12345678

这种情况代表X出现在0号位的情况。

但是其中的 1  2 3 4 5 代表的不是数字,代表的是第一个出现  ,第二个出现,第三个出现,第四个出现,第五个出现的数字(不包括X)。

比如字符串“12X453786”

   第一个出现的字符是“1”,第二个出现的字符是“2”,第三个出现的字符是“4”,第四个是“5”。。。。

所以该字符串可以转换为 12X345678 的形式

然后将其目标串中的每一个字符转换为它在初始串中出现的次序

比如如果“12X453786”的目标串是“12345678X” 那目标串可转换为: 12534867X  (因为原串中3是第五个出现,4是第三个出现,以此类推)

这样我们就可以枚举出所有可能的变化情况。

然后我们可以由目标串推向初始串

 

#include
using namespace std;
#define LL long long
#define M(a,b) memset(a,b,sizeof(a))
const int MAXN = 5e5 +5;
const int INF = 0x3f3f3f3f;
int Case = 1;
int X[4] = {1,0,0,-1};
int Y[4] = {0,-1,1,0};
int op[4] =   {'d','l','r','u'};///要按照字典序大小排列
int HASH[10] = {1,1,2,6,24,120,720,5040,40320};///1~8的阶乘值
char str1[15],str2[15];
int vis[MAXN];
int xb[MAXN];
int hash_num;
struct Node2{
    int pre;
    char c;
}Path[10][MAXN];///记录路径
struct Node
{
    int x,y;
    int num[3][3];
    Node (){}
    Node (char str[])
    {
        int len  = strlen(str);

        for(int i=0; itnum[i])
            {
                sum++;
            }
        }
        ans+=(HASH[i] * sum);
    }
    return ans;
}
void bfs(Node s,int id)
{
    M(Path[id],-1);
    M(vis,0);
    queueq;
    hash_num = get_hashnum(s);
    vis[hash_num] =  1;

    q.push(s);
    while(!q.empty())
    {
        Node temp2 = q.front();
        int x1 = temp2.x;
        int y1 = temp2.y;
        int Prehash_num = get_hashnum(temp2);
        q.pop();
        for(int i=0;i<4;i++)
        {
            Node temp3 = temp2;
            int xx = x1+X[i];
            int yy = y1+Y[i];
            if(xx>=0&&xx<3&&yy>=0&&yy<3)
            {
                swap(temp3.num[x1][y1],temp3.num[xx][yy]);
                int thash_num = get_hashnum(temp3);

                temp3.x = xx;
                temp3.y = yy;

                if(vis[thash_num]) continue;
                else vis[thash_num]  = 1;

                Path[id][thash_num].pre = Prehash_num;
                Path[id][thash_num].c = op[i];
                q.push(temp3);
            }
        }
    }

}
int main()
{
    ///枚举所有的九种情况
    Node temp;
    temp = Node("X12345678");
    bfs(temp,0);
    temp = Node("1X2345678");
    bfs(temp,1);
    temp = Node("12X345678");
    bfs(temp,2);
    temp = Node("123X45678");
    bfs(temp,3);
    temp = Node("1234X5678");
    bfs(temp,4);
    temp = Node("12345X678");
    bfs(temp,5);
    temp = Node("123456X78");
    bfs(temp,6);
    temp = Node("1234567X8");
    bfs(temp,7);
    temp = Node("12345678X");
    bfs(temp,8);

    int t;cin>>t;
    while(t--)
    {
        scanf("%s",str1);
        int j = 0;
        int p;
        for(int i=0;i<9;i++)///把初始串转化为出现次序形式
        {
            if(str1[i]=='X')
            {
                p  = i;
            }
            else
            {
                xb[str1[i]-'0'] =j;///第几个出现的
                j++;
            }
        }
        scanf("%s",str2);
        for(int i=0;i<9;i++)
        {
            if(str2[i]=='X')
            {
                continue;
            }
            else
            {
                str2[i] = xb[str2[i]-'0'] +'1';///目标串的字符在原串是第几个出现的
            }
        }
        temp = Node(str2);
        hash_num = get_hashnum(temp);   ///用康托展开求出目标串的哈希值
        string Strans = "";

        while(hash_num!=-1)///由目标串推出原串
        {
            Strans+=Path[p][hash_num].c;
            hash_num= Path[p][hash_num].pre;
        }
        printf("Case %d: %d\n",Case++,Strans.size()-1);
//        if(Strans.size()-1==0)///加上这个会pe。。。
//        {
//            continue;
//        }
        for(int i=Strans.size()-2;i>=0;i--)///因为是逆序推理,所以输出要逆序输出。
        {
            printf("%c",Strans[i]);
        }
        printf("\n");

    }
    return 0;
}


//322560







/*

2
12X453786
12345678X
564178X23
7568X4123
*/









 

 

你可能感兴趣的:(A星算法,搜索,哈希,康托展开,HDU题解)