Catch that cow bfs + dfs

来源:互联网 发布:四川广电网络招聘 编辑:程序博客网 时间:2024/06/05 22:00

Catch That Cow

Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 142   Accepted Submission(s) : 35
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 - 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: <i>N</i> and <i>K</i>
 

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

 

没错 又是这道题  搜索的题好像没什么好说的  看能看懂 自己写又写不大出来  写了个dfs一直RE

long long  dfs(int n,int m)
{
    if(n>=m)
    return n-m;
    if(m%2==0)
    {
        if(m==2*n)
            return 1;
        else if(2*n<m)
            return dfs(2*n,m)+1;
        else return min(2*n+1-m,m-n);
    }
    else return min(dfs(n+1,m),dfs(n-1,m))+1;
    }

这样数据越来越大 越来越慢

把起始位置之后才解决掉  让牛捉人  一路搜到底

对于bfs 队列的应用是我比较头疼的地方 

#include<iostream>#include<stdio.h>#include<string.h>#include<queue>using namespace std;int vis[100001];int n,m;/*long long  dfs(int n,int m){    if(n>=m)    return n-m;    if(m%2==0)    {        if(m==2*n)            return 1;        else if(2*n<m)            return dfs(n,m/2)+1;        else return min(n+1-m/2,m-n);    }    else return min(dfs(n,m-1),dfs(n,m+1))+1;    }*/struct node{     int x;     int step;}; int bfs() {     int i;     queue<node>Q;     while(!Q.empty())Q.pop();     node now,next;     now.x=n;     now.step=0;     vis[now.x]=1;     Q.push(now);     while(!Q.empty())     {        now=Q.front();        Q.pop();        for(i=0;i<3;i++){             if(i==0)                next.x=now.x-1;             else if(i==1)                next.x=now.x+1;             else                next.x=2*now.x;             next.step=1+now.step;             if(next.x==m)                 return next.step;             if(!vis[next.x]&&next.x>=0&&next.x<=100000)             {                 vis[next.x]=1;                 Q.push(next);             }         }     }     return 0; } int main() {     int ans;     while(cin>>n>>m)     {         memset(vis,0,sizeof(vis));         if(n>=m)cout<<n-m<<endl;         else cout<<bfs()<<endl;         }     return 0; }