2016蓝桥杯省赛C/C++A组第二题 跳蚱蜢
2024-09-30 09:15:27
题意:有9只盘子,排成1个圆圈。 其中8只盘子内装着8只蚱蜢,有一个是空盘。 我们把这些蚱蜢顺时针编号为 1~8 每只蚱蜢都可以跳到相邻的空盘中,也可以再用点力,越过一个相邻的蚱蜢跳到空盘中。 请你计算一下,如果要使得蚱蜢们的队形改为按照逆时针排列, 并且保持空盘的位置不变(也就是1-8换位,2-7换位,...),至少要经过多少次跳跃? 注意:要求提交的是一个整数,请不要填写任何多余内容或说明文字。
分析:结果是20。
#include<bits/stdc++.h>
using namespace std;
set<string> st;
int deal(string s){
int len = s.size();
for(int i = 0; i < len; ++i){
if(s[i] == '0') return i;
}
}
int bfs(){
queue<string> q;
queue<int> step;
q.push("012345678");
step.push(0);
while(!q.empty()){
string s = q.front();
q.pop();
int tmpstep = step.front();
step.pop();
int id = deal(s);
string tmps = s;
int tmpid = (id + 1) % 9;
tmps[id] = s[tmpid];
tmps[tmpid] = s[id];
if(!st.count(tmps)){
if(tmps == "087654321") return tmpstep + 1;
st.insert(tmps);
q.push(tmps);
step.push(tmpstep + 1);
}
tmpid = (id + 2) % 9;
tmps = s;
tmps[id] = s[tmpid];
tmps[tmpid] = s[id];
if(!st.count(tmps)){
if(tmps == "087654321") return tmpstep + 1;
st.insert(tmps);
q.push(tmps);
step.push(tmpstep + 1);
}
tmpid = (id + 8) % 9;
tmps = s;
tmps[id] = s[tmpid];
tmps[tmpid] = s[id];
if(!st.count(tmps)){
if(tmps == "087654321") return tmpstep + 1;
st.insert(tmps);
q.push(tmps);
step.push(tmpstep + 1);
}
tmpid = (id + 7) % 9;
tmps = s;
tmps[id] = s[tmpid];
tmps[tmpid] = s[id];
if(!st.count(tmps)){
if(tmps == "087654321") return tmpstep + 1;
st.insert(tmps);
q.push(tmps);
step.push(tmpstep + 1);
}
}
return -1;
}
int main(){
printf("%d\n", bfs());
return 0;
}
最新文章
- PHP——使用header()函数下载文件
- .NET逻辑分层架构总结
- ASP.NET MVC+WCF+NHibernate+Autofac 框架组合(一)
- SQl函数的写法
- freeCodeCamp:GO BYBY GO!
- cocos js响应过程
- c#中var关键字用法
- ios王云鹤--iPhone中,点击换行,键盘消失。
- C语言库函数大全及应用实例四
- Centos5.5系统备份
- C#的初学知识点
- c++中sizeof的用法
- 关于C++“加、减机制”的整理
- Script error.解决方法
- 玩转EhCache之最简单的缓存框架
- C++文件流操作
- Magnum Kubernetes源码分析(一)
- Windows编程之connect函数研究
- java基础(十) 数组类型
- java.lang.NoClassDefFoundError: Lcom/opensymphony/xwork2/util/logging/Logger tomcat6 启动错误
热门文章
- Spark教程——(3)编写spark-shell测试Demo
- 第3节 storm高级应用:4、5、ack机制,以及其验证超时
- Python Download Image (python + requests + BeautifulSoup)
- 实战mysql存储程序与定时器
- NoSQL技术
- 二、Linux目录结构&;常用指令
- STM32学习笔记:为什么使用外部中断要打开syscfg时钟?
- POJ 3348:Cows 凸包+多边形面积
- 该虚拟机似乎正在使用中 如果该虚拟机未在使用请按获取所权T按钮获取他的所有权,否则,请按取消按钮以防损坏
- ETC系列产品非接触式读卡器方案:SI522