HDU 1043 Eight【A*算法】 【康托展开】【八码问题】 【哈希】

Eight

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 31183    Accepted Submission(s): 8176
Special Judge

 

Problem Description

The 15-puzzle has been around for over 100 years; even if you don't know it by that name, you've seen it. It is constructed with 15 sliding tiles, each with a number from 1 to 15 on it, and all packed into a 4 by 4 frame with one tile missing. Let's call the missing tile 'x'; the object of the puzzle is to arrange the tiles so that they are ordered as:

 1  2  3  4
 5  6  7  8
 9 10 11 12
13 14 15  x


where the only legal operation is to exchange 'x' with one of the tiles with which it shares an edge. As an example, the following sequence of moves solves a slightly scrambled puzzle:

 1  2  3  4     1  2  3  4     1  2  3  4     1  2  3  4
 5  6  7  8     5  6  7  8     5  6  7  8     5  6  7  8
 9  x 10 12     9 10  x 12     9 10 11 12     9 10 11 12
13 14 11 15    13 14 11 15    13 14  x 15    13 14 15  x
            r->            d->            r->


The letters in the previous row indicate which neighbor of the 'x' tile is swapped with the 'x' tile at each step; legal values are 'r','l','u' and 'd', for right, left, up, and down, respectively.

Not all puzzles can be solved; in 1870, a man named Sam Loyd was famous for distributing an unsolvable version of the puzzle, and
frustrating many people. In fact, all you have to do to make a regular puzzle into an unsolvable one is to swap two tiles (not counting the missing 'x' tile, of course).

In this problem, you will write a program for solving the less well-known 8-puzzle, composed of tiles on a three by three
arrangement.

 

 

Input

You will receive, several descriptions of configuration of the 8 puzzle. One description is just a list of the tiles in their initial positions, with the rows listed from top to bottom, and the tiles listed from left to right within a row, where the tiles are represented by numbers 1 to 8, plus 'x'. For example, this puzzle

1 2 3
x 4 6
7 5 8

is described by this list:

1 2 3 x 4 6 7 5 8

 

 

Output

You will print to standard output either the word ``unsolvable'', if the puzzle has no solution, or a string consisting entirely of the letters 'r', 'l', 'u' and 'd' that describes a series of moves that produce a solution. The string should include no spaces and start at the beginning of the line. Do not print a blank line between cases.

 

 

Sample Input

 

2 3 4 1 5 x 7 6 8

 

 

Sample Output

 

ullddrurdllurdruldr

 

 

Source

South Central USA 1998 (Sepcial Judge Module By JGShining)

 

 

Recommend

JGShining

 

 

关于八码问题的介绍:

https://blog.csdn.net/huangxy10/article/details/8034285

 

关于A*算法的介绍:

http://www.cppblog.com/mythit/archive/2009/04/19/80492.aspx

 

在做此八码问题之前,先了解八码问题的一个可解问题:

(此段话摘自博客:https://blog.csdn.net/huangxy10/article/details/8034285)
          八数码问题的一个状态实际上是0~9的一个排列,对于任意给定的初始状态和目标,不一定有解,也就是说从初始状态不一定能到达目标状态。因为排列有奇排列和偶排列两类,从奇排列不能转化成偶排列或相反。
如果一个数字0~8的随机排列871526340,用F(X)表示数字X前面比它小的数的个数,全部数字的F(X)之和为Y=∑(F(X)),如果Y为奇数则称原数字的排列是奇排列,如果Y为偶数则称原数字的排列是偶排列。
例如871526340这个排列的
Y=0+0+0+1+1+3+2+3+0=10
10是偶数,所以他偶排列。871625340
Y=0+0+0+1+1+2+2+3+0=9
9是奇数,所以他奇排列。

所以说明:当原排列是奇排列时无解。

 

如何用康托展开来计算哈希呢?
(此段话摘自于博客:https://blog.csdn.net/iceiceicpc/article/details/52119994)

首先这题必须要用hash和康托展开来压缩空间,康托展开的原理我用一个例子来讲解:
对于这样一个排列:14032,他在排列中排第几呢?公式是:
1*4!+3*3!+0*2!+1*1!+0*0!
求法是这样的,首先看第一个数字1,在数字1前面(不是这个排列的前面,而是这个排列所出现的数字中,如14032中只有一个0比它小)小于它的数只有一个0,对于它后面的数可以有4!种(4的全排列),所以对于1就是1*4!,同理对于4,0~4比它小的有0,1,2,3,但是1在前面已经用过了,所以只有3个,对于后面就是3!,所以对于4就是3*3!,同理往后推。

但是为什么要用hash呢,其实就是为了判重,因为如果你用普通的方法去判重,那么对于3*3方块,每一个数字都有9种可能0~8,况且你用普通bfs和dfs的vis数组根本无法判这题状态是否重复。但是hash可以很好的解决这个问题,因为hash可以把3*3这些数字全部排列的个数控制在0~9!上,对于每一个转态就有一个唯一的hash值,此时只要开一个一维的vis[hash最大值]数组就

 

#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 X[4] = {-1,1,0,0};
int Y[4] = {0,0,-1,1};
int HASH[9]= {1,1,2,6,24,120,720,5040,40320};///0! 1! 2! 3! ......8! 的值
char op[4] = {'u','d','l','r'};///操作名称
char str[30];
int vis[MAXN];
int nx[50];
int END;

struct Node
{
    int num[3][3];
    int x,y;
    int g,f,h;
    int hash_num;
    bool operator <(const Node &k) const///返回搜索价值最大的
    {
        return f>k.f;
    }
} st,ed;
priority_queueq;
struct Node2
{
    int pre;
    char c;
} Path[MAXN];
int get_hash(Node x)///用康托展开来简化哈希。
{

    int tnum[9];
    int len,sum,ans;
    ans = len = sum = 0;
    for(int i=0; i<3; i++)
    {
        for(int j=0; j<3; j++)
        {
            tnum[len++] = x.num[i][j];
        }
    }

    for(int i=0; i<9; i++)
    {
        sum = 0;
        for(int j=0; jtnum[i])///计算逆序数
            {
                sum++;
            }

        }
        ans+=HASH[i]*sum;
    }

    return ans;
}
int get_h(Node x)///曼哈顿距离
{
    int ans = 0;
    for(int i=0; i<3; i++)
    {
        for(int j=0; j<3; j++)
        {
            if(x.num[i][j])
            {
                ans+=abs(i-(x.num[i][j]-1)/3)+abs(j-(x.num[i][j]-1)%3);///计算该位置目标的数和现在此位置上的数的差值。来计算曼哈顿距离。
            }
        }
    }
    return ans;
}
void init()
{
    M(vis,0);
    M(nx,0);
    M(Path,0);
    while(!q.empty()) q.pop();

    for(int i=0; i<9; i++)
    {
        ed.num[i/3][i%3] = (i+1)%9;
    }
    END = get_hash(ed);///求出初始状态的哈希值。
}
void printans(int s)///打印函数
{

    if(Path[s].pre == -1)
    {
        return ;
    }
    printans(Path[s].pre);
    printf("%c",Path[s].c);
}
void A_star(Node x)
{
    M(vis,0);
    st.hash_num = get_hash(st);
    st.g = 0;
    st.h = get_h(st);
    st.f = st.g + st.h;
    vis[st.hash_num] = 1;
    Path[st.hash_num].pre = -1;
    q.push(st);



    if(st.hash_num == END)///开始状态就是终态的话
    {
        printf("\n");
        return;
    }

    while(!q.empty())
    {

        Node top = q.top();
        q.pop();

        for(int i =0; i<4; i++)
        {

            int xx = top.x +X[i];
            int yy = top.y +Y[i];
            if(xx>=0&&xx<3&&yy>=0&&yy<3)
            {

                Node temp = top;
                swap(temp.num[top.x][top.y],temp.num[xx][yy]);
                int temp2 = get_hash(temp);
                if(vis[temp2]==1)
                {
                    continue;
                }
                else
                {
                    vis[temp2] = 1;
                }
                temp.hash_num = temp2;
                temp.x = xx;
                temp.y = yy;
                temp.g++;
                temp.h = get_h(temp);
                temp.f = temp.g+temp.h;


                Path[temp2].pre = top.hash_num;
                Path[temp2].c = op[i];

                if(END == temp2)
                {
                    printans(temp2);
                    printf("\n");
                    return ;
                }

                q.push(temp);
            }
        }

    }
}
int main()
{

    while(gets(str))
    {
        init();
        int len =strlen(str);
        int len2,k,sum;
        len2 = k = sum = 0;

        for(int i=0; inx[i])
                {
                    sum++;
                }
            }
        }
        if(sum&1)///奇数排列无解
        {
            printf("unsolvable\n");
            continue;
        }
        else
        {
            A_star(st);
        }
    }
    return 0;
}

 

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