[poj] Catch That Cow--bfs
2024-09-28 02:51:41
Description
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.
* Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.
If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?
Input
Line 1: Two space-separated integers: N and K
Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Sample Input
5 17
Sample Output
4
Hint
The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
三个搜索方向 +1, -1, *2 用bfs搜索 数组要开到最大值的2倍 注意剪枝和边界问题
#include <iostream>
#include <stdio.h>
#include <queue>
#include <cstring>
using namespace std; const int Max = ;
int s, e;
struct node
{
int x, step;
}now, Next;
bool v[];
queue<node>q; int bfs()
{
now.x = s;
now.step = ;
v[s] = ;
q.push(now);
while (!q.empty()) {
now = q.front();
q.pop();
if (now.x == e)
return now.step; Next.x = now.x*;
Next.step = now.step+;
if (Next.x >= && Next.x <= Max && !v[Next.x]){
q.push(Next);
v[Next.x] = ;
} Next.x = now.x-;
Next.step = now.step+;
if (Next.x >= && Next.x <= Max && !v[Next.x]){
q.push(Next); //若先检查v[Next.x] 会出现数组越界v[-1]的情况
v[Next.x] = ;
} Next.x = now.x+;
Next.step = now.step+;
if (Next.x >= && Next.x <= Max && !v[Next.x]){
q.push(Next);
v[Next.x] = ;
} }
return ;
} int main()
{
//freopen("1.txt", "r", stdin);
cin >> s >> e;
memset(v, , sizeof(v));
cout << bfs(); return ;
}
最新文章
- Windows 使用 Yeoman generators 创建 ASP.NET 应用程序
- jquery给div的innerHTML赋值
- Double Checked Locking 模式
- 使用robot frame selenium中遇到的问题汇总
- nginx beginners_guide
- js阻止提交表单(post)
- jquery dialog open后,服务器端控件失效的快速解决方法
- 细说Mysql四种安装方法及自动化部署
- nova分析(2)—— nova-all
- 给一已经排序数组A和x,求A中是否包含两个元素之和为x
- bzoj 2301 [HAOI2011]Problem b(莫比乌斯反演)
- LaTeX中用BibTex管理参考文献
- MVC自学系列之三(MVC视图-Views)
- gitflow 在windows下的安装方法
- Word,Excel,PowerPoint协作实用功能
- SQL Server AG集群启动不起来的临时自救大招
- zabbix 网络模板自动发现端口时,过滤掉某些特定规则的端口,减少item的方法
- 前端ArcGIS学习之路-引言
- [转帖]50个必知的Linux命令技巧,你都掌握了吗?
- java学习之—栈匹配字符串符号