Catch That Cow----BFS

Catch That Cow

Description

农夫知道一头牛的位置,想要抓住它。农夫和牛都位于数轴上 ,农夫起始位于点 N(0<=N<=100000) ,牛位于点 K(0<=K<=100000) 。农夫有两种移动方式:
1、从 X移动到 X-1或X+1 ,每次移动花费一分钟
2、从 X移动到 2*X ,每次移动花费一分钟
假设牛没有意识到农夫的行动,站在原地不动。农夫最少要花多少时间才能抓住牛?

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  

 

代码一:C++STL&&bfs版本:

代码:

#include<iostream>
#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;
 
const int maxn=100001;
 
bool vis[maxn];//标记数组
int step[maxn];//记录到了每一位置所走的步数
queue <int> q;//定义队列
 
int bfs(int n,int k)
{
    int head,next;
    q.push(n);   //开始FJ在n位置,n入队
    step[n]=0;
    vis[n]=true; //标记已访问
    while(!q.empty())  //当队列非空
    {
        head=q.front();  //取队首
        q.pop();         //弹出对首
        for(int i=0;i<3;i++)     //FJ的三种走法
        {
            if(i==0) next=head-1;
            else if(i==1) next=head+1;
            else next=head*2;
            if(next<0 || next>=maxn) continue; //排除出界情况
            if(!vis[next])  //如果next位置未被访问
            {
                q.push(next);    //入队
                step[next]=step[head]+1;  //步数+1
                vis[next]=true;  //标记已访问
            }
            if(next==k) return step[next];  //当遍历到结果,返回步数
        }
    }
}
int main()
{
    int n,k;
    while(cin>>n>>k)
    {
        memset(step,0,sizeof(step));
        memset(vis,false,sizeof(vis));
        
        while(!q.empty()) q.pop(); //注意调用前要先清空
        if(n>=k) cout<<n-k<<endl;
        else cout<<bfs(n,k)<<endl;
    }
}

代码二:C语言+bfs+模拟队列版本

代码;

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
#define N 100010
struct node{
    int x,step;
}q[N];
int vis[N];
int bfs(int n,int k){
    node now,next;
    int head=0,tail=1;
    q[head].x=n;
    q[head].step=0;
    vis[n]=1;
    while(head<tail){
        now=q[head++];
        for(int i=0;i<3;i++){
            if(i==0) next.x=now.x-1;
            else if(i==1) next.x=now.x+1;
            else if(i==2) next.x=now.x*2;
            if(next.x<0||next.x>N) continue;
            if(!vis[next.x]){
                vis[next.x]=1;
                next.step=now.step+1;
                q[tail++]=next;
            }
            if(next.x==k) return next.step;
        }

    }
}
int main(){
    int n,k;
    scanf("%d%d",&n,&k);
    if(n>=k) printf("%d
",n-k);  
    else printf("%d
",bfs(n,k));
    return 0;
}

 

因上求缘,果上努力~~~~ 作者:每天卷学习,转载请注明原文链接:https://www.cnblogs.com/BlairGrowing/p/13702529.html

原文地址:https://www.cnblogs.com/BlairGrowing/p/13702529.html