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