八数码
2 6 4 1 3 7 0 5 8
8 1 5 7 3 6 4 0 2
31
treap sbt splay
//今天写的八数码 速度不行呀、老超时、照着白皮书写的
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#define MAXSIZE 362888
using namespace std;
typedef int State[9];
State st[MAXSIZE],goal;
int dis[MAXSIZE];
bool hash[MAXSIZE];
int dir[4][2]={0,1,0,-1,1,0,-1,0};
int fac[9],f[MAXSIZE];
bool can_in(State &yy)
{
int c=0,k;
for(int i=0;i<9;i++)
{ k=0;
for(int j=i+1;j<9;j++)
if(yy[j]<yy[i])
k++;
c+=k*fac[8-i];
}
if(hash[c])
return 0;
hash[c]=1;
return 1;
}
int BFS()
{
int i;
int z,newz,x,y,newx,newy;
int first=1,back=2;
State t;
while(first<back)
{
State &s=st[first];
if(memcmp(&s,&goal,sizeof(s))==0) return first;
for(z=0;z<9;z++) if(s[z]==0) break;
x=z/3; y=z%3;
for(i=0;i<4;i++)
{
newx=x+dir[i][0];
newy=y+dir[i][1];
if(newx>=0&&newx<3&&newy>=0&&newy<3)
{
newz=newx*3+newy;
State &t=st[back];
memcpy(&t,&s,sizeof(t));
t[newz]=s[z];
t[z]=s[newz];
if(can_in(t))
{
dis[back]=dis[first]+1;
f[back]=first;
back++;
}
}
}
first++;
}
return 0;
}
char rc[MAXSIZE];
int main()
{
int i;fac[0]=1;
for(i=1;i<9;i++)
fac[i]=fac[i-1]*i;
for(i=0;i<9;i++) goal[i]=(i+1)%9;
f[1]=1;
int hs[133];hs['x']=hs['X']=0;
for(i='1';i<='8';i++)
hs[i]=i-'0';
char c;
while(scanf("%c",&c)!=EOF)
{
st[1][0]=hs[c];i=1;
while(scanf("%c",&c),c!='\n')
{
if(c!=' ') st[1][i++]=hs[c];
}
memset(hash,0,sizeof(hash));
int fa,s=BFS();
i=0;
int zs,zf;
while(f[s]!=s)
{
fa=f[s];
for(zs=0;zs<9;zs++) if(st[s][zs]==0) break;
for(zf=0;zf<9;zf++) if(st[fa][zf]==0) break;
if(zf<zs)
{
if(zs-zf==1)
rc[i++]='r';
else
rc[i++]='d';
}
else
{
if(zf-zs==1)
rc[i++]='l';
else
rc[i++]='u';
}
s=fa;
}
for(s=i-1;s>=0;s--)
printf("%c",rc[s]);
printf("\n");
}
return 0;
}