魔板,状态压缩BFS
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<unordered_map>
#include<queue>
#include<utility>
using namespace std;
unordered_map<string, int> dist; //记录变换到当前状态所需要的步骤数
unordered_map<string, pair<char, string> > pre_s; //记录当前状态的上一个状态时什么,以及如何变化而来的
queue<string> q;
string st, en;
//开始时的序列和目标序列
int g[2][4];
string pull()
{
//数组转字符串
string res;
for (int i = 0; i < 4; i++) {
res.append(1, char(g[0][i]));
}
for (int i = 3;i >=0; i--) {
res.append(1, char(g[1][i]));
}
return res;
}
void push(string t)
{
//字符串转数组
for (int i = 0; i < 4; i++) {
g[0][i] = t[i];
}
for (int i = 3; i >=0; i--) {
g[1][i] = t[7 - i];
}
}
string move_a(string t)
{
//交换上下两行
push(t);
for (int i = 0; i < 4; i++) {
swap(g[0][i], g[1][i]);
}
return pull();
}
string move_b(string t)
{
push(t);
int tmp[2] = {g[0][3], g[1][3]};
for (int i = 3; i > 0; i--) {
g[0][i] = g[0][i - 1];
g[1][i] = g[1][i - 1];
}
g[0][0] = tmp[0];
g[1][0] = tmp[1];
return pull();
}
string move_c(string t)
{
push(t);
int tmp = g[0][1];
g[0][1] = g[1][1];
g[1][1] = g[1][2];
g[1][2] = g[0][2];
g[0][2] = tmp;
return pull();
}
void bfs()
{
dist[st] = 0;
q.push(st);
char mov[] = {'A', 'B', 'C'};
while (!q.empty())
{
string t = q.front();
int d = dist[t];
q.pop();
string m[3];
m[0] = move_a(t);
m[1] = move_b(t);
m[2] = move_c(t);
for (int i = 0; i < 3; i++) {
if (dist.count(m[i]) == 0) {
dist[m[i]] = d + 1;
pre_s[m[i]] = make_pair(mov[i], t);
if (m[i] == en){
return;
}
q.push(m[i]);
}
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("D:/VS CODE/C++/in.txt", "r", stdin);
freopen("D:/VS CODE/C++/out.txt", "w", stdout);
#endif
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 4; ++j) {
int a; cin >> a;
en += char('0' + a);
}
}
st = "12345678";
if (st == en) {
cout << 0;
return 0;
}
bfs();
int d = dist[en];
cout << d << endl;
string p = en;
string ans;
while (p != st) {
ans.append(1, pre_s[p].first);
p = pre_s[p].second;
}
reverse(ans.begin(), ans.end());
cout << ans << endl;
fclose(stdin);
fclose(stdout);
return 0;
}