Eight (八数码 + 康拓展开式)

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 a description of a configuration of the 8 puzzle. The 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.

Sample Input

 2  3  4  1  5  x  7  6  8 

Sample Output

ullddrurdllurdruldr

题意:问从现在这个状态回到完整状态的最小步数,以及路径。

思路:其实想法还是一个bfs,每个状态用 123456780 这种9位数来记录,不过这个9为数太大了,没办法开数组,所以我当时就用map来写。

方法:①.好像是zoj那个八数码问题是有多组数据,所以当时直接从完整状态(123456780)反向搜,到达所有初始状态,然后直接用map<int,string>记录路径就好。不过这种方法在poj1077就超时了。原因很简单嘛,STL极其耗时。

           ②.我们知道耗时的地方主要是STL,所以就要想办法避免STL,那么怎样对状态(123456780)进行记录呢,当然是用哈希了,在这采取康拓展开式(推导不会QAQ)。

康拓展开:(引用 i-Curve的博客

定义:康托展开是一个全排列到一个自然数的双射,常用于构建哈希表时的空间压缩。 康托展开的实质是计算当前排列在所有由小到大全排列中的名次,因此是可逆的。

原理介绍:  X = A[0] * (n-1)! + A[1] * (n-2)! + … + A[n-1] * 0! 

A[i] 指的是位于位置i后面的数小于A[i]值的个数,后面乘的就是后面还有多少个数的阶乘

说明 :这个算出来的数康拖展开值,是在所有排列次序 - 1的值,因此X+1即为在全排列中的次序

eg :在(1,2,3,4,5)5个数的排列组合中,计算 34152的康托展开值。
带入上面的公式

                         X = 2 * 4! + 2 * 3! + 0 * 2! + 1 * 1! + 0 * 0!
                     =>X = 61

康拓展开的构造函数:

//返回数组a中当下顺序的康拖映射
int cantor(int *a,int n)
{
	int ans=0;
	for(int i=0;i<n;i++)
	{
		int x=0;int c=1,m=1;//c记录后面的阶乘
		for(int j=i+1;j<n;j++)
		{
			if(a[j]<a[i])x++;
			m*=c;c++;
		}
		ans+=x*m;
	}
	return ans;
}

逆康拖展开

static const int FAC[] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};   // 阶乘
  
//康托展开逆运算
void decantor(int x, int n)
{
    vector<int> v;  // 存放当前可选数
    vector<int> a;  // 所求排列组合
    for(int i=1;i<=n;i++)
        v.push_back(i);
    for(int i=m;i>=1;i--)
    {
        int r = x % FAC[i-1];
        int t = x / FAC[i-1];
        x = r;
        sort(v.begin(),v.end());// 从小到大排序
        a.push_back(v[t]);      // 剩余数里第t+1个数为当前位
        v.erase(v.begin()+t);   // 移除选做当前位的数
    }
}

八数码AC代码(POJ1077)

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
bool book[3000010];
int dir[4][2]= {0,1, 1,0, 0,-1, -1,0};
char F[]= {"rdlu"};
struct node
{
    int x,y,h,f,step;
    int a[3][3];
} eg[3000010];
int cal(int k) //计算康拓展开值
{
    int sum=0;
    for(int i=0; i<9; i++)
    {
        int ans=0;  //后面比这个数小的个数
        int x=i/3;   //对太懒了,直接用的二维数组 
        int y=i-3*x;
        int c=1,m=1;  //算阶乘
        for(int j=i+1; j<9; j++)//计算
        {
            int tx=j/3;
            int ty=j-3*tx;
            if(eg[k].a[x][y]>eg[k].a[tx][ty])//计数
                ans++;  
            m*=c; //阶乘
            c++;
        }
        sum+=ans*m;//计数
    }
    return sum;
}
void print(int h)
{
    char str[10010];
    int n=0;
    while(h!=-1)
    {
        int f=eg[h].f;
        str[n++]=F[f];
        h=eg[h].h;
    }
    for(int i=n-2; i>=0; i--)  //第一个位置没有方向的
        printf("%c",str[i]);
    printf("\n");
}
void bfs()
{
    int s=0,e=1;
    while(s<e)
    {
        int x=eg[s].x;
        int y=eg[s].y;
        for(int i=0; i<4; i++)
        {
            int tx=x+dir[i][0];
            int ty=y+dir[i][1];
            if(tx<0||ty<0||tx>=3||ty>=3)
                continue;
            eg[e]=eg[s];
            swap(eg[e].a[x][y],eg[e].a[tx][ty]); //直接换0的位置
            int sum=cal(e); //计算康拓展开数值
            if(book[sum])continue;//重复
            book[sum]=1;
            eg[e].step=eg[s].step+1;
            eg[e].h=s;      //记录头节点,方便输出路径
            eg[e].f=i;      //记录方向
            eg[e].x=tx,eg[e].y=ty;
            if(sum==46233) //提前算好结束条件下的康拓展开值
            {
                print(e);
                return;
            }
            e++;
        }
        s++;
    }
    printf("unsolvable\n");
}
int main()
{
    char str[2];
    int a=1;
    for(int i=0; i<3; i++)
        for(int j=0; j<3; j++)
        {
            scanf("%s",str);
            if(str[0]=='x')
            {
                eg[0].x=i,eg[0].y=j;
                eg[0].a[i][j]=0;
            }
            else
            {
                eg[0].a[i][j]=(str[0]-'0');
            }
        }
    eg[0].step=0,eg[0].h=-1;
    eg[0].f=0;
    int x=cal(0);
    book[x]=1;
    bfs();
    return 0;
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值