1318: [蓝桥杯2017初赛]跳蚱蜢

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;
}

仅供个人温习

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值