BFS最短路径(求x到y的最少计算次数)

链接:https://www.nowcoder.com/questionTerminal/45d04d4d047c48768543eeec95798ed6?f=discussion
来源:牛客网
 

给定两个-100到100的整数x和y,对x只能进行加1,减1,乘2操作,问最少对x进行几次操作能得到y?

例如:
a=3,b=11: 可以通过3*2*2-1,3次操作得到11;
a=5,b=8:可以通过(5-1)*2,2次操作得到8;
 

 

输入描述:

输入以英文逗号分隔的两个数字,数字均在32位整数范围内。


 

输出描述:

输出一个数字

示例1

输入

3,11

输出

3
#include<iostream>
#include<unordered_set>
#include<queue>
#include<vector>
using namespace std;

int BFS(int a,int b){
    queue<pair<int,int>> q;
    unordered_set<int> Exist;
    q.push(make_pair(a,0));
    while(!q.empty()){
        auto tmp = q.front();
        q.pop();
        if(tmp.first == b){
            return tmp.second;
        }
        if(Exist.find(tmp.first) != Exist.end()){
            continue;
        }
        Exist.insert(tmp.first);
        q.push(make_pair(tmp.first + 1,tmp.second + 1));
        q.push(make_pair(tmp.first - 1,tmp.second + 1));
        q.push(make_pair(tmp.first * 2,tmp.second + 1));
    }
}

int main(){
    int a,b;
    char c;
    int Result = 0;
    while(cin >> a >> c >> b){
        Result = BFS(a,b);
        cout << Result << endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值