在HDU无压力过,在POJTLE。。。。
#include <iostream>
#include <stack>
#include <queue>
#include <vector>
using namespace std;
int vis[1000000];
int dir[1000000][2];
queue< vector<short> > q;
queue<int> zt;
int start;
int target;
const int dx[] = {
-1, 1, 0 ,0
};
const int dy[] = {
0, 0, -1, 1
};
int fac[9] = {
0, 1, 2, 6, 24, 120, 720, 5040, 40320
};
int kt(vector<short> &temp)
{
int re = 1;
int hash[9] = {
0,0,0,0,0,0,0,0,0
};
for(int i = 0; i < 8; i++){
hash[temp[i]] = 1;
int number = 0;
for(int j = temp[i]-1; j >= 0; j--)
if(!hash[j])
number++;
re += fac[8-i]*number;
}
return re;
}
int main()
{
char temp, counter = 0;
vector<short> vtemp;
vtemp.push_back(1);vtemp.push_back(2);vtemp.push_back(3);
vtemp.push_back(4);vtemp.push_back(5);vtemp.push_back(6);
vtemp.push_back(7);vtemp.push_back(8);vtemp.push_back(0);
zt.push(kt(vtemp));
vis[zt.front()] = 1;
target = zt.front();
q.push(vtemp);
while(!q.empty()){
vector<short> rear = q.front();
q.pop();
int r = zt.front();
zt.pop();
int z;
for(z = 0; z < 9; z++)
if(!rear[z])
break;
int x = z/3, y = z%3;
int newx, newy, newz;
for(int i = 0; i < 4; i++){
newx = x + dx[i];
newy = y + dy[i];
newz = newx*3 + newy;
if(newx >= 0 && newx < 3 && newy >= 0 && newy < 3){
vector<short> newv(rear);
int temp = newv[z];
newv[z] = newv[newz];
newv[newz] = temp;
int newr = kt(newv);
if(!vis[newr]){
vis[newr] = 1;
zt.push(newr);
dir[newr][0] = r;
dir[newr][1] = i;
q.push(newv);
}
}
}
}
while(cin >> temp){
vector<short>vtemp;
vtemp.push_back(temp == 'x' ? 0 : temp - '0');
for(int i = 1; i < 9; i++){
cin >> temp;
if(temp >= '1' && temp <= '8'){
vtemp.push_back(temp-'0');
}else
vtemp.push_back(0);
}
start = kt(vtemp);
bool isanswer = false;
if(vis[start])
isanswer = true;
if(isanswer){
int now = start;
stack<char> out;
while(now != target){
switch(dir[now][1]){
case 0: cout << "d"; break;
case 1: cout << "u"; break;
case 2: cout << "r"; break;
case 3: cout << "l";
}
now = dir[now][0];
}
while(!out.empty()){
cout << out.top();
out.pop();
}
cout << endl;
}else{
cout << "unsolvable" << endl;
}
}
return 0;
}