18年南大考研复试机试题第二题

农夫John的奶牛跑路了。将地图视作一条数轴,John的初始位置在s而奶牛的位置在t(0<=s,t<=100000)。John可以花费一分钟的时间使自己作如下移动:

1 从点x移动到点x+1
2 从点x移动到点x-1
3 从点x移动到点x*2
奶牛的位置一直在点t。现在给定s,t,要求John要追上奶牛最少需要几分钟。

Sample Input:
5 17

Sample Output:
4

Description:
5->4->8->16->17

#include<iostream>
#include<queue>
using namespace std;
const int inf=1000000000;

int d[100010],pre[100010];

void BFS(int s,int t){

    fill(d,d+100010,inf);
    queue<int> q;
    q.push(s);
    d[s]=0;
    while(!q.empty()){
        int a=q.front();
        q.pop();
        if(a+1==t || a-1==t|| a*2==t){
            pre[t]=a;
            d[t]=d[a]+1;
            break;
        }
        if(a-1>0 && d[a-1]>=inf){
            d[a-1]=d[a]+1;
            pre[a-1]=a;
            q.push(a-1);
        }
        if(d[a+1]>=inf){
            d[a+1]=d[a]+1;
            pre[a+1]=a;
            q.push(a+1);    
        }
        if(2*a<=100000 && d[2*a]>=inf){
            d[2*a]=d[a]+1;
            pre[2*a]=a;
            q.push(a*2);
        }
    }
}
void DFS(int s,int t,int x){
    if(s==t){
        cout<<t<<"->";
        return;
    }  
    DFS(s,pre[t],x);
    cout<<t;
    if(x!=t)
        cout<<"->";
    else
        cout<<endl;
}
int main(){

    int s,t;
    while(scanf("%d %d",&s,&t)!=EOF && s>=0 && t>=0){
        if(s==t){
            cout<<0<<endl;
            continue;
        }
        else{
            BFS(s,t);
            cout<<d[t]<<endl;
        }
        DFS(s,t,t);
    }
    
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值