Catch That Cow
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、从 X移动到 X-1或X+1 ,每次移动花费一分钟
2、从 X移动到 2*X
就在函数中判断三种情况即可。第一种:前进一步;第二种:后退一步;第三种:前进二的倍数步。
完整代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
struct node //结构体
{
int num;
int place;
}start;
int n,k;
int vis[100005]; //标记状态(也可以定义成bool型)
int bfs()
{
queue<node>q;
node c,Next;
memset(vis,0,sizeof(vis));
start.num=n;
start.place=0;
q.push(start);
vis[start.num]=1;
while(!q.empty())
{
c=q.front();
q.pop();
if(c.num==k) //正好是就直接retur
{
return c.place;
}
if(c.num-1>=0&&!vis[c.num-1]) //后退一步
{
Next.num=c.num-1;
Next.place=c.place+1;
vis[Next.num]=1;
q.push(Next);
}
if(c.num+1<=100000&&!vis[c.num+1]) //前进一步
{
Next.num=c.num+1;
Next.place=c.place+1;
vis[Next.num]=1;
q.push(Next);
}
if(c.num*2<=100000&&!vis[c.num*2]) //前进2的倍数步
{
Next.num=c.num*2;
Next.place=c.place+1;
vis[Next.num]=1;
q.push(Next);
}
}
}
int main()
{
cin>>n>>k;
int ans=bfs();
cout<<ans<<endl;
return 0;
}
原题链接:
https://vjudge.net/problem/POJ-3278
http://poj.org/problem?id=3278