BFS-1

来源:互联网 发布:python oxc000007b 编辑:程序博客网 时间:2024/06/05 11:39


https://vjudge.net/problem/15204/origin



Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a pointN (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 orX + 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 andK
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.
#include <iostream>#include <queue>#include <cstdio>using namespace std;const int MAX_N=1e5;int N,K;int ans[MAX_N+1];int BFS(){    queue<int>que;    for(int i=0;i<=MAX_N;i++){            ans[i]=0;        }    que.push(N);    while(que.size()){        int tp=que.front();que.pop();        if(tp==K) break;        if(tp+1<=100000&&ans[tp+1]==0){            ans[tp+1]=ans[tp]+1;            que.push(tp+1);        }        if(tp-1>=0&&ans[tp-1]==0){            ans[tp-1]=ans[tp]+1;            que.push(tp-1);        }        if(tp*2<=100000&&ans[tp*2]==0){            ans[tp*2]=ans[tp]+1;            que.push(tp*2);        }    }    return ans[K];}int main(){    while(~scanf("%d%d",&N,&K)){        cout<<BFS()<<endl;    }    return 0;}
这是我仿照迷宫最短路径问题写的代码,要理解DFS为什么要用队列的数据结构;
0 0