1. 程式人生 > >HDU 3567 Eight II 【bfs預處理】【八碼問題】【康託展開】

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

Recommend

zhouzeyong

這題我先按照上一題的A*做法做了一遍,結果超時了。

A*超時版本:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
#include<map>
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];
vector<int>v[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_queue<Node>q;
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; j<i; j++)
        {
            if(num2[j]>num2[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<bits/stdc++.h>
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; i<len; i++)
        {
            if(str[i]=='X')
            {
                num[i/3][i%3] =0;
                x = i/3;
                y = i%3;
            }
            else
            {
                num[i/3][i%3] = str[i]-'0';
            }
        }
    }
};
int get_hashnum(Node s)///康託展開
{
    int tnum[9];
    int len = 0;
    int ans,sum;
    ans = sum = 0;
    for(int i=0;i<3;i++)
    {
        for(int j=0;j<3;j++)
        {
            tnum[len++] = s.num[i][j];
        }
    }
    for(int i=0;i<9;i++)
    {
        sum = 0;
        if(tnum[i]==0)
        {
            continue;
        }
        for(int j=0;j<i;j++)
        {
            if(tnum[j]==0)
            {
                sum++;
                continue;
            }
            else if(tnum[j]>tnum[i])
            {
                sum++;
            }
        }
        ans+=(HASH[i] * sum);
    }
    return ans;
}
void bfs(Node s,int id)
{
    M(Path[id],-1);
    M(vis,0);
    queue<Node>q;
    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
*/