您的位置:首页 > 编程语言 > C语言/C++

第八届蓝桥杯c++大学A组(省赛)——第二题

2018-03-04 19:16 477 查看
(转自博主mylegendarytime)

本题的思路比较浅显,显然广搜。但是实际用程序模拟的过程中,状态不太容易书写与表示。借鉴了一下他人的写法。

#include <cstdio>
#include <string>
#include <queue>
#include <map>
using namespace std;
#define fi first
#define se second
#define pr make_pair
typedef pair<string, int> psi;
const string st = "012345678";
const string ed = "087654321";
const int d[5] = {1, 2, 7, 8};
queue<pair<psi, int> > que;
map<string, string> parent;
int main() {
// 将一个状态用string和字符0在该string中的位置来表示
// 一个状态还会附加上步数
int ans;
parent[st] = "";
que.push(pr(pr(st, 0), 0));
while (!que.empty()) {
string x = que.front().fi.fi;
int pos = que.front().fi.se;
int length = que.front().se;
if (x == ed) {
ans = length;
break;
}
que.pop();
for (int i = 0; i < 4; i++) {
string y = x;
swap(y[pos], y[(pos + d[i]) % 9]);
if (parent.count(y) == 0) {
parent[y] = x;
que.push(pr(pr(y, (pos + d[i]) % 9), length + 1));
}
}
}
printf("ans = %d\n\n", ans);
// 打印蚂蚱跳跃的路径
for (
4000
string now = ed; now != ""; now = parent[now]) {
printf("%s\n", now.c_str());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: