HDU - 1043 Eight (八数码)逆向BFS+康拓展开hash判重+打表
康拓展开
不理解康拓展开的可以学习一下啊:https://blog.csdn.net/laaahu/article/details/96425860
题意:
在九个方格中每个方格都有一个数字,其中一个是x(后面我们会用0表示这个点),所以就是0到8这九个数字在一个3X3的方格里运动,每次x与其相邻的上下左右处的数字可以发生交换,要求的是:
给你一个方格的状态判断是否可以最终达到 1 2 3 4 5 6 7 8 x这种状态。如果可以输出操作步骤
u(上),d(下),l(左),r(右)
思路:
可能大家会想到广搜,可是直接广搜状态数目太多肯定超时,所以我们学习了康拓展开之后就很容易想到这是一个全排列的问题,我们可以利用康拓展开构建hash函数判重会大大缩短时间。
打表是因为如果多组输入我们可以只进行一次bfs然后获得所有结果一定程度会节省时间。
具体一些细节可以看一下代码注释。
还有就是我一直超内存,不要把你每个状态都存下来没必要,这就是为什么我超内存了。只要一个数组来存状态也是完全够的。
AC代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<queue>
#include<vector>
using namespace std;
const int maxn=362885;
const int fac[]={1,1,2,6,24,120,720,5040,40320,362880}; //康拓展开要用到的0~9的阶乘。
bool vis[maxn];
int go[8]={1,0,-1,0,0,1,0,-1}; //四个搜索方向
char index[5]="udlr"; //这个与上面的搜索方向是反的,因为我们是反向搜索
int aim=46234; //对应结果123456780的hash值。
string path[maxn]; //记录路径
int state[9]; //临时状态数组
struct node{
int hash;
int lac; //0的位置
string path;
};
int cantor(int a[]){ //康拓展开求位次
int x=0;
for(int i=0;i<9;i++){
int small=0;
for(int j=i+1;j<9;j++){
if(a[j]<a[i])small++;
}
x+=small*fac[9-i-1];
}
return x+1;
}
void recantor(int *a,int val){ //逆康拓展开将临时数组的状态转为此时的队首状态
vector<int>vv;
for(int i=0;i<9;i++){
vv.push_back(i);
}
for(int i=0;i<9;i++){
int r,s;
r=val/fac[9-i-1];
s=val%fac[9-i-1];
val=s;
sort(vv.begin(),vv.end());
a[i]=vv[r];
vv.erase(vv.begin()+r);
}
}
void bfs(){
memset(vis,false,sizeof(vis));
queue<node>q;
node now,temp;
for(int i=0;i<8;i++)state[i]=i+1;
state[8]=0;
now.lac=8;
now.hash=aim;
now.path="";
path[aim]="";
q.push(now);
vis[aim]=true;
while(!q.empty()){
now=q.front();
q.pop();
for(int i=0;i<8;i+=2){
int xx=now.lac/3+go[i];
int yy=now.lac%3+go[i+1];
if(xx>=0&&xx<=2&&yy>=0&&yy<=2){
temp=now;
temp.lac=xx*3+yy;
recantor(state,now.hash-1); //每次都要记得转状态,因为state一直在变。
swap(state[temp.lac],state[now.lac]); //交换相邻变量
temp.hash=cantor(state); //求的这个状态下的hash值
if(!vis[temp.hash]){
vis[temp.hash]=true;
temp.path=index[i/2]+temp.path;
q.push(temp);
path[temp.hash]=temp.path;
}
}
}
}
return ;
}
int main()
{
node cur;
bfs(); //直接打表。
char s;
while(cin>>s){
if(s=='x'){
cur.lac=0;
state[0]=0;
for(int i=1;i<=8;i++){
cin>>s;
state[i]=s-'0';
}
}
else{
state[0]=s-'0';
for(int i=1;i<=8;i++){
cin>>s;
if(s=='x'){
state[i]=0;
cur.lac=i;
}
else{
state[i]=s-'0';
}
}
}
cur.hash=cantor(state);
if(!vis[cur.hash])cout<<"unsolvable"<<endl;
else{
cout<<path[cur.hash]<<endl;
}
}
return 0;
}