BFSCatch That Cow(POJ3278)
Posted 路人姜。
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了BFSCatch That Cow(POJ3278)相关的知识,希望对你有一定的参考价值。
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
Output
Sample Input
5 17
Sample Output
4
Hint
Source
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
queue <int> que;
int times[100001];//记录花费的时间
int visited[100001];//标记数组,比如x*2已经到达的地方标记下来,x+1到达时就不需要走这了,因为x*2更快
int bfs(int n,int k);
int main()
{
int N,K;//N:FJ,K:cow
scanf("%d%d",&N,&K);
que.push(N);
times[N]=0;
visited[N]=1;
printf("%d\n",bfs(N,K));
return 0;
}
int bfs(int n,int k){
while(!que.empty()){
int t1=que.front();
que.pop();
int t;
for(int i=0;i<3;i++){//遍历三种方式,相当于在图中遍历四个方向
t=t1;
if(i==0){
t=t+1;
}
else if(i==1){
t=t-1;
}
else{
t=t*2;
}
//因为N的范围是0~100000所以可能越界
///刚开始我没考虑到,就runtime error了。。
if(t<0||t>100001)
continue;
if(visited[t]==0){
que.push(t);
visited[t]=1;
times[t]=times[t1]+1;
}
if(t==k){
return times[t];
}
}
}
}
参考自:http://blog.csdn.net/freezhanacmore/article/details/8168265
以上是关于BFSCatch That Cow(POJ3278)的主要内容,如果未能解决你的问题,请参考以下文章