USACO Magic Squares 魔板 【BFS-HASH】

Description
  在成功地发明了魔方之后,拉比克先生发明了它的二维版本,称作魔板。这是一张有 8 8 8个大小相同的格子的魔板:
1 2 3 4
8 7 6 5
  我们知道魔板的每一个方格都有一种颜色。这8种颜色用前8个正整数来表示。可以用颜色的序列来表示一种魔板状态,规定从魔板的左上角开始,沿顺时针方向依次取出整数,构成一个颜色序列。对于上图的魔板状态,我们用序列( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 1,2,3,4,5,6,7,8 12345678)来表示。这是基本状态。
  这里提供三种基本操作,分别用大写字母 “ A ” , “ B ” , “ C ” “A”,“B”,“C” ABC来表示(可以通过这些操作改变魔板的状态):
“ A ” “A” A:交换上下两行;
“ B ” “B” B:将最右边的一列插入最左边;
“ C ” “C” 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
  对于每种可能的状态,这三种基本操作都可以使用。
  你要编程计算用最少的基本操作完成基本状态到目标状态的转换,输出基本操作序列。


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

Output
L i n e 1 : Line 1: Line1: 包括一个整数,表示最短操作序列的长度。
L i n e 2 : Line 2: Line2: 在字典序中最早出现的操作序列,用字符串表示,除最后一行外,每行输出 60 60 60个字符。


Sample Input
2 6 8 4 5 7 3 1

Sample Output
7
BCABCCB


解题思路
该题目很明显是用搜索做,如果用深度优先搜索,则可能出现死循环,而且时间很长,所以只能用宽度优先搜索。但是如果没有一种好的方法来判断是否已经加入列表,时间可能会超时,所以,我想到了哈希表。按照初始状态标号,则共有 8 ! = 40320 8!=40320 8=40320个情况。根据公式:
可以将每一种情况唯一对应到 0   40319 0~40319 0 40319中的一个数。再用宽度优先搜索可以很轻松的实现这一算法。


代码

#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int m=100003;
const int rule[3][8]={{8,7,6,5,4,3,2,1},{4,1,2,3,6,7,8,5},{1,7,2,4,5,3,6,8}};
int x,fa[m],num[m],l[m],h,t;
string a,st[m],bsy[m];
bool hash(string x){//判断字状态x是否存在,存在返回True,不存在添加在hash表中
	int k=0;
	for(int i=0;i<8;i++)
		k=(k<<3)+(k<<1)+x[i]-48;//(k<<3)+(k<<1)=k*10
	int i=0;
	k%=m;
	while(i<m&&bsy[(i+k)%m]!=""&&bsy[(i+k)%m]!=x)
		i++;
	if(bsy[(i+k)%m]=="")
	{
		bsy[(i+k)%m]=x;	
		return 0;
	}
	else
		return 1;
}
void bfs()
{
	hash("12345678");
	st[1]="12345678";
	h=0,t=1;
	while(h<t)
	{
		h++;
		for(int i=0;i<3;i++)
		{
			t++;
			st[t]="";
			fa[t]=h;
			num[t]=num[h]+1;
			if(i==0)l[t]='A';
			else if(i==1)l[t]='B';
			else if(i==2)l[t]='C';
			for(int j=0;j<8;j++)
				st[t]+=st[h][rule[i][j]-1];
			if(hash(st[t]))//利用hash表判重
				t--;
			else
				if(st[t]==a)
				return;
		}
	}
}
void write(int x)
{
	if(x==1)return;
	write(fa[x]);
	printf("%c",l[x]);
}
int main(){
	for(int i=0;i<8;i++)
	{
		scanf("%d",&x);
		a+=x+48;
	}
	if(a=="12345678")
		printf("0");
	else
	{
		bfs();
		printf("%d\n",num[t]);
		write(t);
	}
}
		
			

### 解题思路 "The Lost Cow" 是一道经典的模拟问题,目标是计算 Farmer John 找到 Bessie 需要行走的距离。Farmer John 使用一种特定的策略来寻找 Bessie:他从初始位置 `x` 开始,依次向右走一段距离,再返回原点;接着向左走更远的一段距离,再次回到原点,如此反复直到找到 Bessie。 #### 关键逻辑 1. **移动模式** 每次移动的距离按照序列 \( \pm 1, \mp 2, \pm 4, \ldots \) 增加,即每次翻倍并改变方向。 2. **终止条件** 当 Farmer John 到达的位置覆盖了 Bessie 的实际坐标 `y` 时停止搜索。具体来说: - 如果 `x < y`,则当某一次移动到达或超过 `y` 时结束; - 如果 `x > y`,则当某一次移动到达或低于 `y` 时结束。 3. **总路径长度** 计算总的路径长度时需要注意最后一次未完全完成的往返行程应减去多余的部分。 --- ### C++ 实现代码 以下是基于上述逻辑的一个标准实现: ```cpp #include <iostream> #include <cmath> using namespace std; int main() { long long x, y; cin >> x >> y; if (x == y) { cout << 0; return 0; } long long pos = x, step = 1, total_distance = 0; while (true) { // 向右移动 long long next_pos = pos + step; if ((x < y && next_pos >= y) || (x > y && next_pos <= y)) { total_distance += abs(y - pos); break; } total_distance += abs(next_pos - pos); pos = next_pos; // 返回起点 total_distance += abs(pos - x); // 向左移动 step *= -2; next_pos = pos + step; if ((x < y && next_pos >= y) || (x > y && next_pos <= y)) { total_distance += abs(y - pos); break; } total_distance += abs(next_pos - pos); pos = next_pos; // 返回起点 total_distance += abs(pos - x); step *= -2; } cout << total_distance; return 0; } ``` 此代码实现了 Farmer John 寻找 Bessie 的过程,并精确计算了所需的总路径长度[^1]。 --- ### Pascal 实现代码 如果偏好 Pascal,则可以参考以下代码片段: ```pascal var n, x, y, t, ans: longint; begin assign(input, 'lostcow.in'); reset(input); assign(output, 'lostcow.out'); rewrite(output); readln(x, y); if x = y then begin writeln(0); halt; end; n := x; t := 1; ans := 0; repeat ans := ans + abs(t) + abs(n - x); n := x + t; t := -t * 2; if ((n >= y) and (x < y)) or ((n <= y) and (x > y)) then begin ans := ans - abs(n - y); break; end; until false; writeln(ans); close(input); close(output); end. ``` 这段代码同样遵循相同的逻辑结构,适用于需要提交至 USACO 平台的情况[^3]。 --- ### Python 实现代码 对于初学者而言,Python 提供了一种更为简洁的方式表达这一算法: ```python def lost_cow(x, y): if x == y: return 0 position = x step = 1 total_distance = 0 while True: # Move to the right new_position = position + step if (x < y and new_position >= y) or (x > y and new_position <= y): total_distance += abs(new_position - position) total_distance -= abs(new_position - y) break total_distance += abs(new_position - position) position = new_position total_distance += abs(position - x) # Move to the left step *= -2 new_position = position + step if (x < y and new_position >= y) or (x > y and new_position <= y): total_distance += abs(new_position - position) total_distance -= abs(new_position - y) break total_distance += abs(new_position - position) position = new_position total_distance += abs(position - x) return total_distance # Example usage print(lost_cow(int(input()), int(input()))) ``` 该版本通过逐步调整步长和方向完成了整个搜索流程[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值