USACO: Magic Squares

本文介绍了一个基于平面的魔方版本——魔法方块,并详细解释了其配置变化的三种基本转换方法:交换顶底行(A)、单次右旋(B)及中间四格顺时针旋转(C)。通过哈希函数与广度优先搜索(BFS)算法,实现从初始配置到目标配置的最短路径计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Magic Squares
IOI'96

Following the success of the magic cube, Mr. Rubik invented its planar version, called magic squares. This is a sheet composed of 8 equal-sized squares:

1234
8765

In this task we consider the version where each square has a different color. Colors are denoted by the first 8 positive integers. A sheet configuration is given by the sequence of colors obtained by reading the colors of the squares starting at the upper left corner and going in clockwise direction. For instance, the configuration of Figure 3 is given by the sequence (1,2,3,4,5,6,7,8). This configuration is the initial configuration.

Three basic transformations, identified by the letters `A', `B' and `C', can be applied to a sheet:

  • 'A': exchange the top and bottom row,
  • 'B': single right circular shifting of the rectangle,
  • 'C': single clockwise rotation of the middle four squares.

Below is a demonstration of applying the transformations to the initial squares given above:

A:
8765
1234
B:
4123
5876
C:
1724
8635

All possible configurations are available using the three basic transformations.

You are to write a program that computes a minimal sequence of basic transformations that transforms the initial configuration above to a specific target configuration.

PROGRAM NAME: msquare

INPUT FORMAT

A single line with eight space-separated integers (a permutation of (1..8)) that are the target configuration.

SAMPLE INPUT (file msquare.in)

2 6 8 4 5 7 3 1 

OUTPUT FORMAT

Line 1: A single integer that is the length of the shortest transformation sequence.
Line 2: The lexically earliest string of transformations expressed as a string of characters, 60 per line except possibly the last line.

SAMPLE OUTPUT (file msquare.out)

7
BCABCCB

 

思路:

哈希(我用的哈希函数是康托展开)+BFS

话说哈希确实是一个极有探究价值的东东,康托用来哈希组合状态是今天才学的,懂了一点原理之后,康托函数也是自己鼓捣出来的,弄好之后再和书上的比较,发现我的思路略微不同,不过效率也不差呀!

 

提交的第一个版本顺利通过所有测试,最慢的一个也就0.043s

 

然后我看代码有点冗长(A、B、C三个函数并排展开写),就写了个函数指针数组来缩减代码,结果提交后奇怪地出现了越界错误,注意,下面的代码是第二个版本的,maxsize加了10之后又通过了测试,最慢0.067s,看来简洁的东西不一定有效率啊

 

输出字符串是逆向的,所以我干脆用字符指针倒移,这样算是违规操作吧?嘿嘿


最后,我在写这个题解的时候才发现一个郁闷的问题:我忘了"60 per line"这事,但是程序通过了测试!难道数据太弱了?

 

不过想想也是,按照完全的操作三叉树,60层深度,3^60已经达到了恐怖的42391158275216203514294433201,大概是4*10E28,就算中间剪掉了很多枝叶,60的深度也应该足够覆盖全部状态8!(40320)了吧?可见做事还是要经大脑好点……

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值