题目链接:
[kuangbin带你飞]专题一 简单搜索 - Virtual Judgehttps://vjudge.net/contest/65959#problem/C
求最短操作数问题, bfs水题。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
typedef long long ll;
const int maxn = 2e6;
int n, k;
queue<int> q;
bool vis[maxn]; // 是否遍历过该点
int cnt[maxn]; // 到该点的最小操作数
int bfs(){
// 处理起点
q.push(n);
cnt[n] = 0;
vis[n] = true;
while(q.size()){
int cur = q.front(); q.pop();
int next;
for(int i=0; i<3; i++){
// 三种处理方式
if(i == 0) next = cur + 1;
else if(i == 1) next = cur - 1;
else next = cur * 2;
if(next < 0 || next >= maxn || vis[next]) continue; // 除去越界的元素,和遍历过的元素
//处理当前next点
q.push(next);
vis[next] = true;
cnt[next] = cnt[cur] + 1;
if(next == k) return cnt[next];
}
}
return -1; // 不可能到这里
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> n >> k;
if(n >= k) {cout << n-k << endl; return 0;} // 剪枝
cout << bfs() << endl;
}