您的位置:首页 > 其它

[USACO3.2]魔板 Magic Squares

2017-08-05 10:41 399 查看
Magic Squares 魔板

IOI'96


目录

 [隐藏
1 描述
2 格式
3 SAMPLE
INPUT
4 SAMPLE
OUTPUT


[编辑]描述

在成功地发明了魔方之后,鲁比克先生发明了它的二维版本,称作魔板。这是一张有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


对于每种可能的状态,这三种基本操作都可以使用。

你要编程计算用最少的基本操作完成基本状态到目标状态的转换,输出基本操作序列。


[编辑]格式

PROGRAM NAME: msquare

INPUT FORMAT:

(file msquare.in)

只有一行,包括8个整数,用空格分开(这些整数在范围 1——8 之间)不换行,表示目标状态。

OUTPUT FORMAT:

(file msquare.out)

Line 1: 包括一个整数,表示最短操作序列的长度。

Line 2: 在字典序中最早出现的操作序列,用字符串表示,除最后一行外,每行输出60个字符。


[编辑]SAMPLE
INPUT

2 6 8 4 5 7 3 1


[编辑]SAMPLE
OUTPUT

7
BCABCCB


【题解】

/*
ID:luojiny1
LANG:C++
TASK:msquare
*/
#include<queue>
#include<string>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<set>
using namespace std;
int gold[8];
struct State{
int st[8],dist;
string s;
};
set<int>v;
bool Try(int s[8]){
int x=0;
for(int i=0;i<8;i++)x=x*10+s[i];
if(v.count(x))return false;
v.insert(x);
return true;
}
bool pd(int x[8]){
for(int i=0;i<8;i++)if(x[i]!=gold[i])return false;
return true;
}
void bfs()
{
queue<State>Q;
v.insert(12345678);
Q.push((State){{1,2,3,4,5,6,7,8},0,""});
while(!Q.empty()){
State x=Q.front();Q.pop();
if(pd(x.st)){
cout<<x.dist<<endl<<x.s<<endl;return;
}
State now;
now.dist=x.dist+1;
now.st[0]=x.st[7],now.st[1]=x.st[6],now.st[2]=x.st[5],now.st[3]=x.st[4],now.st[4]=x.st[3],now.st[5]=x.st[2],now.st[6]=x.st[1],now.st[7]=x.st[0];
if(Try(now.st)){
now.s=x.s+"A";Q.push(now);
}
now.st[0]=x.st[3],now.st[1]=x.st[0],now.st[2]=x.st[1],now.st[3]=x.st[2],now.st[4]=x.st[5],now.st[5]=x.st[6],now.st[6]=x.st[7],now.st[7]=x.st[4];
if(Try(now.st)){
now.s=x.s+"B";
Q.push(now);
}
now.st[0]=x.st[0],now.st[1]=x.st[6],now.st[2]=x.st[1],now.st[3]=x.st[3],now.st[4]=x.st[4],now.st[5]=x.st[2],now.st[6]=x.st[5],now.st[7]=x.st[7];
if(Try(now.st)){
now.s=x.s+"C";
Q.push(now);
}
}
}
int main()
{
freopen("msquare.in","r",stdin);
freopen("msquare.out","w",stdout);
for(int i=0;i<8;i++)cin>>gold[i];
v.clear();
bfs();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: