catch that cow POJ 3278 搜索

题意

原题链接

john想要抓到那只牛,John和牛的位置在数轴上表示为n和k,john有三种移动方式:1. 向前移动一个单位,2. 向后移动一个单位,3. 移动到当前位置的二倍处。输出移动的最少次数。

解题思路

使用搜索,准确地说是广搜,要记得到达的位置要进行标记,还有就是减枝。

详情见代码实现。

代码实现

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=1e5+7; //这个是数轴的最大尺度
int n, k, ans=inf;
struct node{
int x, t;
};
map<int, int> mp; //使用map进行标记
queue<node> q;
void bfs(int x)
{
mp.clear();
int tx;
node h={x, 0};
q.push(h);
mp[x]=1; //起点也要进行标记
while(!q.empty() )
{
h=q.front();
q.pop();
tx=h.x+1;
if(mp[tx]==0)
{
if(tx == k)
{
ans=min(ans, h.t+1);
return ;
}
//只有当john的位置小于牛的位置时,进行加一操作才有意义
else if(tx < k && tx<maxn)
{
node tmp={tx, h.t+1};
q.push(tmp);
mp[tx]=1;
}
}
tx=h.x-1;
if(mp[tx]==0)
{
if(tx == k)
{
ans=min(ans, h.t+1);
return ;
}
else if(tx >= 0)//减一操作后要判断是不是小于0
{
node tmp={tx, h.t+1};
q.push(tmp);
mp[tx]=1;
}
}
tx=h.x<<1;
if(mp[tx]==0)
{
if(tx == k)
{
ans=min(ans, h.t+1);
return ;
}
else if( h.x < k && tx<maxn) //只有起点小于k时,乘2操作开可以进行
{
node tmp={tx, h.t+1};
q.push(tmp);
mp[tx]=1;
}
}
}
}
int main()
{
scanf("%d%d", &n, &k);
if(n==k)
ans=0;
else bfs(n);
printf("%d\n", ans);
return 0;
}

最新文章

  1. input标签中button在iPhone中圆角的问题
  2. Disable the screen switching about VI
  3. 【转】adb控台中Permission denied的解决方案
  4. DotNET知识点总结三(笔记整合)
  5. cocos2d-x游戏开发系列教程-搭建cocos2d-x的windows开发环境
  6. xx-net 使用方式
  7. mysql安装后服务启动不了(总结)
  8. 《算法 (第4版)》【PDF】下载
  9. POJ 2104 K-th Number 主席树
  10. 子RelativeLayout与layout_alignParentBottom属性会撑大视图
  11. [Codeforces113C]Double Happiness(数论)
  12. 【netcore基础】.Net core通过 Lucene.Net 和 jieba.NET 处理分词搜索功能
  13. MariaDB ColumnStore初探(1):安装、使用及测试
  14. Linux中用find命令查找当前文件夹下的.elf文件
  15. 协程的NullReferenceException 错误
  16. excel快速访问工具栏和自定义选项卡
  17. SQL Server 商业智能
  18. CFGym 101505I 题解
  19. 关于Cookie跨域的问题研究
  20. Blue Jeans---poj3080(kmp+暴力求子串)

热门文章

  1. rmq——同步、异步、单向、rocketMQ console、消费模式
  2. css-div中文字过多(内容超出div宽度)后自动换行
  3. forEach、map、filter、reduce的区别
  4. vue发布到iis
  5. memset设置最大值
  6. DVWA--upload
  7. RestTemplate 调用本地服务 connection refused
  8. 如何解决两个相邻的span中间有空隙
  9. C/C++题库
  10. @清晰掉 Sizeof与字符串