poj3278之BFS

来源:互联网 发布:商城二次开发 php 编辑:程序博客网 时间:2024/06/14 03:52
Catch That Cow
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 89698 Accepted: 28138

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 - 1 or + 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.


题目大意:有一个人和一头牛处在x轴上的不同位置,现在人要尽快地到达牛所处的位置,已知人有3种走法,向前进一步,向后退一步,以及自己的位置坐标翻倍(x=2*x),这三种方法已知都是耗时1分钟,现在求最少分钟,人可以到达牛的位置。


题目分析:这题我用的是BFS,直接暴力出每一种走法,然后当遇到牛所在的位置坐标时,输出步数,结束循环。


代码:

#include <queue>#include <iostream>using namespace std;#define size 2000000int visit[size]={0};        //记载步数以及标记是否被访问过int main(){    int n,m;    queue<int>que;    cin>>n>>m;    int now,next;    now=n;    que.push(now);    while(!que.empty()){        now=que.front();        que.pop();        if(now==m){                 //当遇到牛时结束循环            cout<<visit[now]<<endl;            break;        }        for(int i=0;i<3;i++){       //向队列中加入未访问的坐标(要注意不加next<=100000数据会超出int存储范围)            if(i==0) next=now+1;            else if(i==1) next=now-1;            else next=now*2;            if(!visit[next]&&next<=100000){                que.push(next);                visit[next]=visit[now]+1;            }        }    }    return 0;}


0 0
原创粉丝点击