POJ 3278 Catch That Cow (BFS)
来源:互联网 发布:unity3d awake start 编辑:程序博客网 时间:2024/06/02 01:50
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
题意
农夫需要找到他的牛,农夫现在所在位置是N,牛在K点,假设牛是不动的,农夫有三种走法:
- 向前走一步(N+1)
- 向后走一步(N-1)
- 跳到当前位置两倍处(2*N)
问,最少走多少次才能找到他的牛。
思路
简单的bfs,把农夫当前位置加入队列,然后出队判断每一个点,并模拟下一次的走法,注意的是,需要标记走过的点,否则会爆栈。
AC代码
#include <iostream>#include<stdio.h>#include<stdlib.h>#include<string.h>#include<queue>#include<math.h>#define MAXX 100005using namespace std;bool isvisted[MAXX];struct node{ int n; int time; node(int n,int time) { this->n=n; this->time=time; }};void bfs(int n,int k){ memset(isvisted,false,sizeof(isvisted)); node ans=node(n,0); isvisted[n]=true; queue<node>sk; sk.push(ans); while(!sk.empty()) { node p=sk.front(); sk.pop(); isvisted[p.n]=true; //标记走过的点 if(p.n==k) //找到 { ans=p; break; } if(p.n+1<MAXX&&!isvisted[p.n+1]) //三种走法 sk.push(node(p.n+1,p.time+1)); if(p.n-1>=0&&!isvisted[p.n-1]) sk.push(node(p.n-1,p.time+1)); if(p.n*2<MAXX&&!isvisted[p.n*2]) sk.push(node(p.n*2,p.time+1)); } printf("%d\n",ans.time);}int main(){ int n,k; while(~scanf("%d%d",&n,&k)) bfs(n,k); return 0;}
- poj 3278 Catch That Cow BFS
- poj 3278 Catch That Cow BFS
- POJ 3278 Catch That Cow BFS
- poj 3278 bfs(Catch That Cow)
- poj 3278 Catch That Cow(bfs)
- POJ 3278 Catch That Cow bfs
- POJ 3278 Catch That Cow 【bfs+队列】
- POJ 3278 Catch That Cow (BFS)
- POJ 3278 Catch That Cow(BFS)
- poj 3278 Catch That Cow bfs
- poj 3278 Catch That Cow (BFS剪枝)
- POJ 3278 Catch That Cow[BFS]
- Poj 3278 Catch That Cow 裸bfs
- POJ 3278 Catch That Cow(图论:BFS)
- POJ 3278 Catch That Cow (BFS)
- POJ 3278 Catch That Cow (BFS)
- poj 3278 Catch That Cow 【BFS】
- POJ--3278:Catch That Cow (BFS)
- SylixOS CAN总线报文浅析
- 创建表空间时UNIFORM SIZE的通俗含义(翻译)
- Hibernate中持久化类
- HTTP协议分析系列(四)------重定向
- Mixed Content Blocking导致Firefox23 无法显示iframe
- POJ 3278 Catch That Cow (BFS)
- c函数之gettimeofday()函数获取系统时间
- vijos P1066弱弱的战壕
- Java web项目 在线网络考试数据库连接部分代码
- 申请美国名校条件一览 雅思成绩对申请者有最大裨益
- python初学者要注意的问题
- jpa hibernate分页查询
- HTTP协议分析系列(五)------php+socket编程发送http请求
- 学习记录3