从目标解开始广搜,就是打表,记录所有可以到目标解的路径,在HDU很容易超空间。
传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1043
#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int ctarray[10] ={1,1,2,6,24,120,720,5040,40320,362880};
int vis[400005];
int ct(int * a){
int i,j,con,ans=0;
for(i=0;i<8;i++){
con = 0;
for(j=i+1;j<9;j++){
if(a[j]<a[i]){
con ++;
}
}
ans += con * ctarray[8-i];
}
return ans;
}
typedef struct L{
int a[10];
int p,pos;
string step;
}L;
string d = "udlr";
int dirtx[4] = {1,-1,0,0};
int dirty[4] = {0,0,1,-1};
int xx,yy;
string zans[400005];
void bfs(){
queue<L>q;
int i;
L now,next;
memset(vis,0,sizeof(vis));
for(i=0;i<8;i++){
now.a[i] = i + 1;
}
now.a[8] = 0;
now.p = ct(now.a);
now.pos = 8;
now.step = "";
q.push(now);
vis[now.p] = 1;
zans[now.p] ="";
while(!q.empty()){
now = q.front();
q.pop();
for(i=0;i<4;i++){
xx = now.pos/3 + dirtx[i];
yy = now.pos%3 + dirty[i];
if(xx<0||xx>2||yy<0||yy>2)continue;
next = now;
next.pos = xx*3 + yy ;
next.a[now.pos] = next.a[next.pos];
next.a[next.pos] = 0;
next.p = ct(next.a);
if(!vis[next.p]){
next.step += d[i];
vis[next.p] = 1;
zans[next.p] = next.step;
q.push(next);
}
}
}
}
void pt(int * a){
int tt = ct(a);
if(!vis[tt]){
puts("unsolvable");
return;
}
for(int i=zans[tt].length()-1;i>=0;i--){
printf("%c",zans[tt][i]);
}
puts("");
}
int main(void){
//freopen("a.in","r",stdin);
bfs();
char tempa[100];
int i,t[10],k;
while(gets(tempa)){
k = 0;
for(i=0;i<strlen(tempa);i++){
if(tempa[i]>='0'&&tempa[i]<='9'){
t[k++] = tempa[i] - '0';
}
if(tempa[i]=='x'){
t[k++] = 0;
}
}
pt(t);
}
return 0;
}