题目描述:
在成功地发明了魔方之后,鲁比克先生发明了它的二维版本,称作魔板。这是一张有8个大小相同的格子的魔板:
1 2 3 4
8 7 6 5
我们知道魔板的每一个方格都有一种颜色。这8种颜色用前8个正整数来表示。可以用颜色的序列来表示一种魔板状态,规定从魔板的左上角开始,沿顺时针方向依次取出整数,构成一个颜色序列。对于上图的魔板状态,我们用序列(1,2,3,4,5,6,7,8)来表示。这是基本状态。
这里提供三种基本操作,分别用大写字母“A”,“B”,“C”来表示(可以通过这些操作改变魔板的状态):
“A”:交换上下两行;
“B”:将最右边的一列插入最左边;
“C”:魔板中央四格作顺时针旋转。
下面是对基本状态进行操作的示范:
A:
8 7 6 5
1 2 3 4
B:
4 1 2 3
5 8 7 6
C:
1 7 2 4
8 6 3 5
对于每种可能的状态,这三种基本操作都可以使用。
你要编程计算用最少的基本操作完成基本状态到目标状态的转换,输出基本操作序列。
【输入格式】
输入有多组测试数据
只有一行,包括8个整数,用空格分开(这些整数在范围 1——8 之间),表示目标状态。
【输出格式】
Line 1: 包括一个整数,表示最短操作序列的长度。
Line 2: 在字典序中最早出现的操作序列,用字符串表示,除最后一行外,每行输出60个字符。
样例输入:
2 6 8 4 5 7 3 1
样例输出:
7
BCABCCB
实现代码:
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <string>
#include <map>
#include <queue>
#include <stack>
using namespace std;
int temp[10] = { 1,1,2,6,24,120,720,5040,40320,362880 };
int dis[500000] = { 0 };//状态标记
char ch[3] = { 'A','B','C' };//三种操作
typedef struct Node {
string s;
char op;
int pre;
}Node;//记录操作和操作结果以及上一个操作
Node operate[90000];
int front = 0, last = 0;
int kangtuo(string s) {//康托公式
int sum = 0;
for (int i = 0; i < s.length() - 1; i++) {
int total = 0;
for (int j = i + 1; j < s.length(); j++) {
if (s[j] < s[i]) {
total++;
}
}
sum += total * temp[s.length() - i - 1];
}
return sum;
}
string swap(string s, int i, int j) {//交换函数
char ch;
ch = s[i];
s[i] = s[j];
s[j] = ch;
return s;
}
string move(string s, int i) {//操作函数
if (i == 1) {
s = swap(s, 0, 7);
s = swap(s, 1, 6);
s = swap(s, 2, 5);
s = swap(s, 3, 4);
}
if (i == 2) {
for (int j = 3; j > 0; j--) {
s = swap(s, j, j - 1);
}
for (int j = 4; j < 7; j++) {
s = swap(s, j, j + 1);
}
}
if (i == 3) {
s = swap(s, 1, 6);
s = swap(s, 6, 5);
s = swap(s, 5, 2);
}
return s;
}
int BFS(string t) {
string s = "12345678";//初始状态
dis[kangtuo(s)] = 1;
Node temp;
temp.s = s;
temp.pre = -1;
temp.op = 'N';
operate[last++] = temp;
while (front != last) {
Node u = operate[front];
if (u.s == t) {
return front;
}
for (int i = 1; i <= 3; i++) {
string v = move(u.s, i);
if (dis[kangtuo(v)] == 0) {//是新状态则入队列
Node temp;
temp.s = v;
temp.pre = front;
temp.op = ch[i - 1];
operate[last++] = temp;
dis[kangtuo(v)] = 1;
}
if (v == t) {
return last - 1;
}
}
front++;
}
return -1;
}
string NumberToString(int a[][4]) {//数组转字符串
string s;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
s += ('0' + a[i][j]);
}
}
return s;
}
void Print(int i) {//输出信息
stack<char> st;
int num = 0;
while (i != 0) {
st.push(operate[i].op);
i = operate[i].pre;
num++;
}
printf("%d\n", num);
while (!st.empty()) {
printf("%c", st.top());
st.pop();
}
printf("\n");
}
int main() {
int a[2][4];
string t;
while (1) {
front=last=0;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
if (scanf("%d", &a[i][j]) == EOF) {
return 0;
}
}
}
t = NumberToString(a);
int ans = BFS(t);
if (ans != -1) {
Print(ans);
}
memset(dis, 0, sizeof(dis));
}
return 0;
}