1151. 魔板
Constraints
Time Limit: 1 secs, Memory Limit: 32 MB , Special Judge
Description
题目和A题相同,在这里我们把数据范围扩大:N可能超过10。
请仔细考虑各种情况。Input
输入包括多个要求解的魔板,每个魔板用三行描述。
第一行步数N,表示最多容许的步数。
第二、第三行表示目标状态,按照魔板的形状,颜色用1到8的表示。
当N等于-1的时候,表示输入结束。Output
对于每一个要求解的魔板,输出一行。
首先是一个整数M,表示你找到解答所需要的步数。接着若干个空格之后,从第一步开始按顺序给出M步操作(每一步是A、B或C),相邻两个操作之间没有任何空格。
注意:如果不能达到,则M输出-1即可。Sample Input
45 8 7 64 1 2 338 7 6 51 2 3 4-1
Sample Output
2 AB
1 A
Submit
这是道关于广度优先搜索状态空间树结合全排列的hash函数设计题,跟简单魔板相比数据更大。如果还是直接采用广搜就会超时,必须对状态空间树进行剪枝,以减少复杂度。利用康托展开进行设计hash函数,标记已经访问过的节点,只将未访问过的状态节点进行进队处理,从而达到将访问过的状态节点以及其衍伸出来的状态子树剪枝。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
struct status
{
int up[4],down[4]; // 表示魔板的上下两行
string op; // 表示从初始态到此状态的操作序列
}begin, target;
bool color[45000];
//康托展开因子
int fac[] = {1,1,2,6,24,120,720,5040,40320};
//康托展开求序列进行求哈希值
int cantor(struct status curr)
{
int sum=0;
int a[8];
for(int i=0; i<4; i++)
{
a[i] = curr.up[i];
a[i+4] = curr.down[i];
}
for(int i=0; i<8; i++)
{
int num=0;
for(int j=i; j<8; j++)
{
if(a[i] > a[j])
num++;
}
sum = sum+num*fac[7-i];
}
return sum;
}
status operation(struct status curr, int operation)
{
struct status next=curr;
//A操作:上下行互换
if(operation == 1)
{
for(int i=0; i<4; i++)
{
int tmp = next.up[i];
next.up[i] = next.down[i];
next.down[i] = tmp;
}
next.op = next.op+"A";
}
//B操作:行循环右移一个
if(operation == 2)
{
int a=next.up[3];
int b=next.down[3];
for(int i=3; i>0; i--)
{
next.up[i] = next.up[i-1];
next.down[i] = next.down[i-1];
}
next.up[0] = a;
next.down[0] = b;
next.op = next.op+"B";
}
//C操作:中间四小块顺时针转一格
if(operation == 3)
{
int tmp = next.up[1];
next.up[1] = next.down[1];
next.down[1] = next.down[2];
next.down[2] = next.up[2];
next.up[2] = tmp;
next.op = next.op+"C";
}
return next;
}
//判断两个转态是否相等
bool is_match(struct status a, struct status b)
{
for(int i=0; i<4; i++)
{
if(a.up[i]!=b.up[i] || a.down[i]!=b.down[i])
return false;
}
return true;
}
// 利用广度优先进行对状态序列树进行扫描
void bfs(int max)
{
if(is_match(begin,target) )
{
cout<<0<<endl;
return;
}
queue<struct status> q;
q.push(begin);
color[cantor(begin)] = true;
while(!q.empty())
{
struct status curr = q.front();
q.pop();
if(curr.op.size() > max)
{
cout<<-1<<endl;
return ;
}
if(is_match(curr, target) )
{
cout<<curr.op.size()<<" "<<curr.op<<endl;
return;
}
for(int i=1; i<4; i++)
{
struct status next;
next = operation(curr, i);
int index = cantor(next);
if(color[index])
continue;
q.push(next);
color[index] = true;
}
}
}
int main()
{
int n;
int tmp;
while(cin>>n && n!=-1)
{
for(int i=0; i<4; i++)
{
begin.up[i] = i+1;
begin.down[i] = 8-i;
target.up[i] = i;
target.down[i] = 8-i;
}
begin.op = "";
target.op = "";
for(int i=0; i<4; i++)
{
cin>>tmp;
target.up[i] = tmp;
}
for(int i=0; i<4; i++)
{
cin>>tmp;
target.down[i] = tmp;
}
memset(color,false,sizeof(color));
bfs(n);
}
// system("pause");
return 0;
}