POJ-3278&&HDU-2717--Catch That Cow---BFS广搜

来源:互联网 发布:什么是数据存储 编辑:程序博客网 时间:2024/05/18 18:21

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
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.

题意:给两个点 a,b。一开始牛在a,每次走的步数都可以为a-1 a+1 a*2.问走到点b最少需要几步。

解题思路:如果a>=b,那么直接输出a-b。否则,将每一个可能要走的步数入队,记录步数用了一个num数组。简述一下num数组的作用:
现在奶牛在点为5的位置上,让num[5]=0。现在与5相关的点有10,4,6。这是要走的第一步,于是num[10]=num[5]+1,num[4]=num[5]+1,num[6]=num[5]+1。以此类推,直到找到点b,num[b]的值就是牛走的最短的步数。

#include<iostream>#include<queue>#include<cstring>using namespace std;int n,k;const int M=1e5;int flag[2*M+50];//数组要开到2*M,因为如果牛已经走到第10W步的时候,20W也要入队。int num[2*M+50];queue<int>q;void bfs(){    q.push(n);    flag[n]=1;    while(!q.empty())    {        int t=q.front();        q.pop();        int t1=t+1,t2=t-1,t3=t*2;        if(t1==k||t2==k||t3==k)        {            num[k]=num[t]+1;            break;        }        if(t1<=2*M&&!flag[t1])        {            q.push(t1);            flag[t1]=1;            num[t1]=num[t]+1;        }        if(t2>=0&&!flag[t2])        {            q.push(t2);            flag[t2]=1;            num[t2]=num[t]+1;        }        if(t3<=2*M&&!flag[t3])        {            q.push(t3);            flag[t3]=1;            num[t3]=num[t]+1;        }    }}int main(){    while(cin>>n>>k)    {        memset(flag,0,sizeof(flag));        memset(num,0,sizeof(num));        while(!q.empty())            q.pop();        if(n>=k)            cout<<n-k<<endl;        else        {            bfs();            cout<<num[k]<<endl;        }    }}