思路:
BFS。
BFS的目标就是求最短(可能是最短路径长度,可能是最短路径)。
本题就是通过BFS来求最短路径长度。
每次有三个方向来扩展状态(想象成三叉树)。
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <algorithm>
#include <fstream>
#include <cmath>
#include <cstring>
#include <limits.h>
#define Long long long
#define uint unsigned int
#define N
#define mod 1000000007
#define inf 100005
#define eps 1e-10
#define For(i,l,r) for(int i=l;i<=r;i++)
#define Dor(i,r,l) for(int i=r;i>=l;i--)
using namespace std;
ifstream in("/Users/urey/data/input.txt");
//_________________________________________________________________________________
int gcd(int a, int b) {
if(b == 0)
return a;
return gcd(b, a%b);
}
int n ,k;
queue<int> q;
int step[inf];
bool visit[inf];
int head;
int bfs() {
q.push(n);
step[n] = 0;
visit[n] = 1;
while(!q.empty()) {
head = q.front();
q.pop();
if(head == k) {
return step[head];
}
//方向一
if(head * 2 < inf && !visit[head * 2]) {
q.push(head*2);
visit[head*2] = 1;
step[head*2] = step[head] + 1;
}
//方向二
if(head + 1 < inf && !visit[head + 1]) {
q.push(head + 1);
visit[head + 1] = 1;
step[head + 1] = step[head] + 1;
}
//方向三
if(head - 1 >= 0 && !visit[head - 1]) {
q.push(head - 1);
visit[head - 1] = 1;
step[head - 1] = step[head] + 1;
}
}
return -1;
}
int main(int argc, const char * argv[]) {
cin>>n>>k;
if(n >= k) {
cout<<n-k<<endl;
}else {
cout<<bfs()<<endl;
}
return 0;
}
BFS求解最短路径
1134

被折叠的 条评论
为什么被折叠?



