问题 D: 【宽搜入门】魔板
时间限制: 1 Sec 内存限制: 128 MB
提交: 184 解决: 44
[提交][状态][讨论版][命题人:外部导入]
题目描述
在成功地发明了魔方之后,鲁比克先生发明了它的二维版本,称作魔板。这是一张有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个字符。
Sample Input
2 6 8 4 5 7 3 1
Sample Output
7
BCABCCB
比之前有进步,比较顺利的就AC了,依旧使用map来实现状态标记
话不多说,上代码:
#include<iostream>
#include<map>
#include<string>
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std;
struct node
{
int a[8]; //状态2*4的矩阵
string path; //路径
int step; //步数
};
map<int, bool> M; //用map实现状态标记
char op[3] = { 'A','B','C' }; //三种操作
int my_hash(node &t)
{
int p = 0;
for (int i = 0; i < 8; i++) //将矩阵转换为一个整数
{
p = p * 10 + t.a[i];
}
return p;
}
bool sta_change(node &t,int n) //三种变换
{
if (n == 0) //交换上下两行
{
for (int i = 0; i < 4; i++)
{
swap(t.a[i], t.a[i + 4]);
}
if (M[my_hash(t)] == 0)return true;
}
if (n == 1) //最右列插入最左列
{
int temp1 = t.a[3], temp2 = t.a[7];
for (int i = 3; i >= 1; i--)
{
t.a[i] = t.a[i - 1];
t.a[i + 4] = t.a[i - 1 + 4];
}
t.a[0] = temp1;
t.a[4] = temp2;
if (M[my_hash(t)] == 0)return true;
}
if (n == 2) //中间四格顺时针旋转
{
int temp1 = t.a[6];
t.a[6] = t.a[2];
t.a[2] = t.a[1];
t.a[1] = t.a[5];
t.a[5] = temp1;
if (M[my_hash(t)] == 0)return true;
}
return false;
}
int main()
{
node start, end;
while (cin >> end.a[0])
{
start.a[0] = 1, start.a[1] = 2, start.a[2] = 3, start.a[3] = 4, start.a[4] = 8, start.a[5] = 7, start.a[6] = 6, start.a[7] = 5; //初始矩阵
M[my_hash(start)] = 1;
start.path =end.path="";
start.step = end.step=0; //一些初始化
for (int i = 1; i < 4; i++)
{
cin >> end.a[i];
}
for (int i = 7; i >= 4; i--)
{
cin >> end.a[i];
}
queue <node> Q;
Q.push(start);
int flag = 0;
while (!Q.empty())
{
node vn = Q.front();
Q.pop();
for (int i = 0; i <3; i++)
{
node temp = vn;
if (sta_change(temp, i)) //可行的操作
{
M[my_hash(temp)] = 1;
temp.step = vn.step + 1; //步长+1
temp.path += op[i]; //加上当前操作
if (my_hash(temp) == my_hash(end)) //如果到达了目标状态
{
end.path = temp.path;
end.step = temp.step;
flag = 1;
break;
}
Q.push(temp);
}
}
if (flag)break;
}
cout << end.step << endl;
for (int i = 0; i < 60; i++) //输出
{
if (i < end.path.length())
cout << end.path[i];
else cout << " ";
}
cout << endl;
}
return 0;
}
AC截图:
最后:种一棵树最好是十年前,其次是现在