天天看點

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;
}