题目链接: https://vjudge.net/contest/65997#problem/B
题意: 略;
思路: 这道写了一晚上一直过不了,也找不到错误的答案,心态快要爆炸,好不容易样例过了,却死在爆内存,我内心真是……,看了别人的题解然后自己写也是一直过不了,一直找不出bug,不知道那里细节出问题,这种巨大代码量的题目对于我来说真是要命,直接贴博客上大佬的Y390d的题解吧
题解链接: https://blog.csdn.net/godleaf/article/details/86990674
#include <iostream>
#include <queue>
#include <cstring>
#include <string>
#include <map>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
const int Maxn = 4e5+10;
struct Node {
int pre, step;
char c;
} node[11][Maxn];
struct nNode {
char str[10];
int pos, st, step;
};
char ch[5] = "dlru", s[10][10] = {"012345678", "102345678", "120345678", "123045678", "123405678",
"123450678", "123456078", "123456708", "123456780"}, ans[50];
int dir[4][2] = { {1, 0}, {0, -1}, {0, 1}, {-1, 0} }, n[15], Hash[10];
bool vis[Maxn];
int cantor(char *ss) {
int ret = 0;
for(int i = 0; i < 9; ++i) {
int cnt = 0;
for(int j = i+1; j < 9; ++j) {
if(ss[j] < ss[i]) cnt++;
}
ret += n[8-i]*cnt;
}
return ret;
}
void bfs(int x) {
memset(vis, false, sizeof(vis));
queue<nNode> qu;
int state = cantor(s[x]);
vis[state] = true;
nNode tmp;
tmp.pos = x; tmp.st = state; tmp.step = 0;
memcpy(tmp.str, s[x], sizeof(tmp.str));
qu.push(tmp);
while (!qu.empty()) {
tmp = qu.front(); qu.pop();
for(int i = 0; i < 4; ++i) {
nNode now = tmp;
int pi, pj;
pi = now.pos/3+dir[i][0]; pj = now.pos%3+dir[i][1];
if(pi < 0 || pi > 2 || pj < 0 || pj > 2) continue;
swap(now.str[pi*3+pj], now.str[now.pos]);
now.pos = pi*3+pj;
state = cantor(now.str);
if(vis[state]) continue;
vis[state] = true;
node[x][state].c = ch[i]; node[x][state].pre = tmp.st;
node[x][state].step = tmp.step+1;
now.st = state; now.step = tmp.step+1;
qu.push(now);
}
}
}
void init() {
for(int i = 0; i < 10; ++i)
for(int j = 0; j < Maxn; ++j) node[i][j].pre = -1;
n[0] = 1;
for(int i = 1; i <= 10; ++i) n[i] = n[i-1]*i;
for(int i = 0; i < 9; ++i) bfs(i);
}
int main(void)
{
int T;
init();
scanf("%d", &T);
for(int cas = 1; cas <= T; ++cas) {
char str1[10], str2[10];
scanf("%s%s", str1, str2);
int pos;
for(int i = 0; i < 9; ++i) {
if(str1[i] == 'X') {
str1[i] = '0'; pos = i;
}
if(str2[i] == 'X') str2[i] = '0';
}
for(int i = 0; i < 9; ++i) Hash[str1[i]-'0'] = s[pos][i]-'0';
for(int i = 0; i < 9; ++i) str2[i] = Hash[str2[i]-'0']+'0';
str2[9] = '\0';
int state = cantor(str2);
int cnt = node[pos][state].step;
int p = cnt;
printf("Case %d: %d\n", cas, cnt);
while (node[pos][state].pre != -1) {
ans[--cnt] = node[pos][state].c;
state = node[pos][state].pre;
}
ans[p] = '\0';
printf("%s\n", ans);
}
return 0;
}
代码出自上面的大佬–Y390d