1318: [蓝桥杯2017初赛]跳蚱蜢
题目链接:http://oj.ecustacm.cn/problem.php?id=1318
该题答案:20,直接输出20即可
方法一:map判重,queue队列
方法一:使用map判重,queue;
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#include<queue>
using namespace std;
typedef struct Node {
string s;
int pos;//0的位置
int index;//移动第几次
Node() {}
Node(string ss, int pp ,int index) :s(ss), pos(pp),index(index){}
}node;
map<string, bool> mmp;
queue<node> qq;
int main() {
string s = "012345678";
qq.push(node(s, 0, 0));
mmp[s] = true;
while (!qq.empty()) {
node temp = qq.front();
qq.pop();
if (temp.s == "087654321") {
cout << temp.index;
break;
}
for (int i = temp.pos - 2; i <= temp.pos + 2; i++) {
if ((i+9)%9 == temp.pos) continue;
swap(temp.s[temp.pos], temp.s[(i+9)%9]);
if (!mmp[temp.s]) {
mmp[temp.s] = true;
qq.push(node(temp.s, (i + 9) % 9, temp.index + 1));
}
swap(temp.s[temp.pos], temp.s[(i + 9) % 9]);
}
}
return 0;
}
方法二:set判重,queue队列
基本思路相同,map变为set。
//方法二:set判重,
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<set>
#include<queue>
using namespace std;
typedef struct Node {
string s;
int pos;//0的位置
int index;//移动第几次
Node() {}
Node(string ss, int pp, int ii) {
s = ss, pos = pp, index = ii;
}
}node;
set<string> vis;
queue<node> qq;
int main() {
string s = "012345678";
qq.push(node(s, 0, 0));
vis.insert(s);
while (!qq.empty()) {
node temp = qq.front();
qq.pop();
if (temp.s == "087654321") {
cout << temp.index;
break;
}
for (int i = temp.pos - 2; i <= temp.pos + 2; i++) {
if ((i + 9) % 9 == temp.pos) continue;
swap(temp.s[temp.pos], temp.s[(i + 9) % 9]);
if (!vis.count(temp.s)) {
vis.insert(temp.s);
qq.push(node(temp.s, (i + 9) % 9, temp.index + 1));
}
swap(temp.s[temp.pos], temp.s[(i + 9) % 9]);
}
}
return 0;
}
仅供个人温习