USACO3.2.5 Magic Squares (msquare)

这篇博客介绍了如何利用宽度优先搜索(BFS)策略解决USACO竞赛中的3.2.5 Magic Squares问题。通过创建状态节点、维护队列和避免重复状态,逐步构造目标方阵。代码实现中,博主展示了如何交换方阵中的数字来尝试所有可能的变换路径,直到找到解决方案。

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

标准的宽搜,应该没什么难度吧。
/*
ID:shijiey1
PROG:msquare
LANG:C++
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <iostream>
#include <queue>
#include <map>

using namespace std;

struct Node {
	int deep;
	string stat, trans;
	Node() {
		stat = "        ";
		trans = "";
	}
};

string start = "12345678";
string end = "";
queue<Node> q;
map<string, int> done;
int main() {
	freopen("msquare.in", "r", stdin);
	freopen("msquare.out", "w", stdout);
	int t;
	for (int i = 0; i < 8; i++) {
		scanf("%d", &t);
		end += t + '0';
	}
	Node node;
	node.stat = start;
	node.trans = "";
	node.deep = 0;
	q.push(node);
	done[start] = 1;
	while (!q.empty()) {
		Node now = q.front();
		q.pop();
		if (now.stat == end) {
			cout << now.deep << endl << now.trans << endl;
			break;
		}
		Node next = Node();
		next.deep = now.deep + 1;

		next.trans = now.trans + 'A';
		for (int i = 0; i < 4; i++) {
			next.stat[i] = now.stat[7 - i];
			next.stat[7 - i] = now.stat[i];
		}
		if (!done[next.stat]) {
			q.push(next);
			done[next.stat] = 1;
		}
		next.trans = now.trans + 'B';
		for (int i = 0; i < 4; i++) {
			next.stat[i] = now.stat[(i + 3) % 4];
			next.stat[i + 4] = now.stat[(i + 5) % 4 + 4];
		}
		if (!done[next.stat]) {
			q.push(next);
			done[next.stat] = 1;
		}
		next.trans = now.trans + 'C';
		next.stat[0] = now.stat[0];
		next.stat[3] = now.stat[3];
		next.stat[4] = now.stat[4];
		next.stat[7] = now.stat[7];
		next.stat[1] = now.stat[6];
		next.stat[2] = now.stat[1];
		next.stat[5] = now.stat[2];
		next.stat[6] = now.stat[5];
		if (!done[next.stat]) {
			q.push(next);
			done[next.stat] = 1;
		}
	}

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值