0
点赞
收藏
分享

微信扫一扫

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


 

给定两个-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;
}

 

举报

相关推荐

0 条评论