Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 23233 | Accepted: 10249 | Special Judge |
Description
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 x
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->
Input
1 2 3 x 4 6 7 5 8
1 2 3 x 4 6 7 5 8
Output
Sample Input
2 3 4 1 5 x 7 6 8
Sample Output
ullddrurdllurdruldr
Source
#include
#include
#include
#include
using namespace std;
const int N = 5;
const int M = 400000;
struct Point{
int x;
int num;
char str[10];
int pre;
int dir;
}fr, next, start, prev[M];
int mp[N][N];
int cv[9][4]={-1, 1,-1, 3,//l r u d
0, 2,-1, 4,
1,-1,-1, 5,
-1, 4, 0, 6,
3, 5, 1, 7,
4,-1, 2, 8,
-1, 7, 3,-1,
6, 8, 4,-1,
7,-1, 5,-1};
int vis[M];
int fac[8] = {1, 2, 6, 24, 120, 720, 5040, 40320};
char buf[10];
char dirr[4] = {'l', 'r', 'u', 'd'};
int cantor(char *s){
int sum = 0;
for(int i = 0; i < 8; i++){
int c = 0;
for(int j = i + 1; j < 9; j++) if(s[i] > s[j]) c++; // 比它小的数表示已经在这位置填过了
sum += c * fac[7 - i];
}
return sum;
}
void print(int y){
if(y == start.num) return;
print(prev[y].pre);
printf("%c", prev[y].dir);
}
void bfs(){
queue Q;
Q.push(start);
while(!Q.empty()){
fr = Q.front();
Q.pop();
if(fr.num == 0){
print(fr.num);
putchar('\n');
return;
}
for(int i = 0; i < 4; i++){
if(cv[fr.x][i] != -1){
memset(buf, '\0', sizeof(buf));
memcpy(buf, fr.str, 9);
char t = buf[fr.x];
buf[fr.x] = buf[cv[fr.x][i]];
buf[cv[fr.x][i]] = t;
int cant = cantor(buf);
if(!vis[cant]){
// cout << buf << endl;
next.x = cv[fr.x][i];
memcpy(next.str, buf, 9);
next.num = cant;
vis[cant] = 1;
Q.push(next);
prev[next.num].pre = fr.num;
prev[next.num].dir = dirr[i];
}
}
}
}
puts("unsolvable");
return;
}
int main(){
char c;
for(int i = 0; i < 9; i++){
while((c = getchar()) == ' ');
if(c == 'x'){
start.str[i] = '9';
start.x = i;
}
else start.str[i] = c;
}
// cout << start.x << endl;
// cout << start.str << endl;
start.num = cantor(start.str);
memset(vis, 0, sizeof(vis));
vis[start.num] = 1;
bfs();
return 0;
}
/*
2 3 4 1 5 x 7 6 8
1 2 3 4 5 6 7 x 8
1 2 3 4 5 x 7 8 6
1 2 3 4 x 5 7 8 6
1 2 3 4 5 x 6 7 8
*/