AcWing 1107. 魔板
原题链接
简单
作者:
郭松源
,
2021-02-27 18:37:14
,
所有人可见
,
阅读 290
#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
#include <queue>
#include <unordered_map>
#include <vector>
using namespace std;
#define x first
#define y second
typedef pair<string, int> node;
string start = "12345678", target;
unordered_map<string, pair<string, char>> pre;
string optionA(string s) {
for (int i = 0; i < 4; i++) swap(s[i], s[7 - i]);
return s;
}
string optionB(string s) {
s = s[3] + s.substr(0, 3) + s.substr(5, 3) + s[4];
return s;
}
string optionC(string s) {
int a = s[1], b = s[2], c = s[5], d = s[6];
s[2] = a, s[5] = b, s[6] = c, s[1] = d;
return s;
}
int bfs() {
queue<node> q;
q.push({ start, 0 });
if (start == target) return 0;
while (!q.empty()) {
node t = q.front();
q.pop();
string s[3];
s[0] = optionA(t.x);
s[1] = optionB(t.x);
s[2] = optionC(t.x);
for (int i = 0; i < 3; i++) {
if (pre.count(s[i]) == 0) {
char op;
if (i == 0) op = 'A';
else if (i == 1) op = 'B';
else op = 'C';
if (s[i] == target) {
pre[s[i]] = { t.x, op };
return t.y + 1;
}
q.push({ s[i], t.y + 1 });
pre[s[i]] = { t.x, op };
}
}
}
return -1;
}
int main() {
char c;
for (int i = 0; i < 8; i++) {
cin >> c;
target += c;
}
int t = bfs();
cout << t << endl;
string path;
string s = target;
if (t) {
while (true) {
path = pre[s].y + path;
s = pre[s].x;
if (s == start) break;
}
cout << path << endl;
}
return 0;
}