HDU 2717 Catch That Cow

来源:互联网 发布:中南大学网络教育学费 编辑:程序博客网 时间:2024/05/21 17:49

Catch That Cow

Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6804    Accepted Submission(s): 2157


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.Ps:题意 一个人要找他的奶牛在一条直线上 这个人只能有三种走法 一. 向前一步二. 向后一步三. 跳到该位置的二倍处 (但不能超过100000, 假设x=50001,牛在100000处 就不能跳到2*50001处 只能向右一步一步走) 最短路径问题利用STL队列实现AC代码
#include<stdio.h>#include<iostream>#include <algorithm>#include<string.h>#include<queue>using namespace std;int a[100010];    //到这一步用的步数int vis[100010];  //是否被访问int bfs(int x,int y){    int i,t;    queue< int > q;    memset(vis,0,sizeof(vis));    memset(a,0,sizeof(a));    q.push(x);    vis[x]=1;    while(!q.empty())    {        x=q.front();        q.pop();        if(x-1==y||x+1==y||x*2==y)            return a[x]+1;        if(vis[x+1]==0&&x+1<=100000&&x+1>=0)        {            q.push(x+1);            a[x+1]=a[x]+1;            vis[x+1]=1;        }        if(x-1<=100000&&vis[x-1]==0&&x-1>=0)        {            q.push(x-1);            a[x-1]=a[x]+1;            vis[x-1]=1;        }        if(x*2>=0&&x*2<=100000&&vis[x*2]==0)        {            q.push(x*2);            a[x*2]=a[x]+1;            vis[x*2]=1;        }    }}int main(){    int x,y,t,ans;    while(cin >> x >> y)    {        if(x<y) ans=bfs(x,y);           else                  //如果牛在人的前面  只能向后走            ans=x-y;        cout << ans <<endl;    }    return 0;}


0 0
原创粉丝点击