题解报告:hdu 2717 Catch That Cow(bfs)

Problem 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.
解题思路:典型的bfs求最少时间。记录每个位置是否被访问,并且用一个结构体来标记每个从初始位置到达某个正访问的位置(之前为未访问)所花费的时间,有三次操作,每次操作都必须在原来的位置上进行位置转移,详解看代码。
AC代码:
 1 #include<iostream>
 2 #include<queue>
 3 #include<string.h>
 4 using namespace std;
 5 const int maxn=1e5+10;
 6 int n,k,cnt;bool vis[maxn];//标记是否访问
 7 struct node{int x,step;}nod;//标记达到当前位置的步数
 8 queue<node> que;
 9 void bfs(int x){
10     while(!que.empty())que.pop();//清空
11     memset(vis,false,sizeof(vis));
12     nod.x=n,nod.step=0;vis[x]=true;//同时将初始位置x标记为true
13     que.push(nod);//先将初始位置入队
14     while(!que.empty()){
15         nod=que.front();que.pop();
16         if(nod.x==k){cout<<nod.step<<endl;return;}//这一步不能忘记,不然会出错,如果当前节点的值和k相等,则直接返回所花费的时间为0
17         for(int i=0;i<3;++i){//遍历三次操作,查看是否还有可以到达的地方
18             node next=nod;//每一次操作都从原来那个位置到另一个位置
19             if(i==0)next.x-=1;
20             else if(i==1)next.x+=1;
21             else next.x*=2;
22             next.step++;//到达对应位置的时间在原来的基础上加1
23             if(next.x==k){cout<<next.step<<endl;return;}//如果到达终点,则直接返回所花费的时间
24             if(next.x>=0&&next.x<maxn&&!vis[next.x]){//如果下一个位置在0~10^5范围内,并且还未访问,就可以将其入队
25                 vis[next.x]=true;//将其标记为已访问状态
26                 que.push(next);//将下一个位置入队
27             }
28         }
29     }
30 }
31 int main(){
32     while(cin>>n>>k){bfs(n);}
33     return 0;
34 }

 

posted @ 2018-08-07 20:29  霜雪千年  阅读(140)  评论(0编辑  收藏  举报