Catch That Cow

来源:互联网 发布:mac桌面的文件不见了 编辑:程序博客网 时间:2024/05/03 11:53

算法:BFS

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

代码:

#include <iostream>#include <stdio.h>#include <cstring>#include <iomanip>#include <algorithm>#include <queue>using namespace std;int a[400005];struct dot{int x,step;};void bfs(int n,int m){   memset(a,0,sizeof(a));queue<dot>que;dot cur,loer;cur.x=n;cur.step=0;a[n]=1;que.push(cur);while(que.size()){loer=que.front();que.pop(); if(loer.x==m){cout<<loer.step<<endl;break;}for(int i=0;i<3;i++){if(i==0)cur.x=loer.x+1;else if(i==1)cur.x=loer.x-1;else cur.x=loer.x*2;if(cur.x>=0&&!a[cur.x]&&cur.x<200005)//一定要加上cur.x<200005 {cur.step=loer.step+1;a[cur.x]=1;que.push(cur);}}}}int main(){int n,m,i,j,k;while(cin>>n>>m)bfs(n,m);return 0;}


0 0