題目:
Problem Description
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.* Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?
Input
Line 1: Two space-separated integers: N and K
Output
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Sample Input
5 17
Sample Output
4
Hint
The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
題目的意思也不難:給你兩個數(shù),一個是起點,另一個是終點。
求出從起點到終點所用的最小操作次數(shù)。
有三種操作方式:
對當(dāng)前數(shù)加1;對當(dāng)前數(shù)-1;對當(dāng)前數(shù)*2.
這道題可以用廣搜的方法。
參考代碼:
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 100000+10;
int dir[3] = {-1, 1, 2};//三個方向值,分別代表三種不同的操作;
struct node {
int x;//當(dāng)前結(jié)點的值;
int step;//此時已經(jīng)經(jīng)過了多少步;
} que[N];//隊列的思想;
int map[N];//已訪問過的;
int bfs(int s, int t) {
memset(map, 0, sizeof(map));
memset(que, 0, sizeof(que));
int l = 0, r = 0;//相當(dāng)于隊首和隊尾指針;
node S;//存放起點;
S.x = s;
S.step = 0;
map[s] = 1;
que[r++] = S;//push操作;
node p;
while (r > l) {//隊列不為空;
p = que[l++];//提取加Pop操作;
if (p.x == t) return p.step;//已經(jīng)找到;
node q;
for (int i = 0;i < 3;++i) {//三種情況的循環(huán);
int nx;
if (p.x > t) {//超過t之后再增加只會越加越遠(yuǎn);
nx = p.x - 1;
}
else if (p.x < t) {
if (i == 2) {
nx = p.x * dir[i];
}
else {
nx = p.x + dir[i];
}
}
if (nx >= 0 && nx <= 100000 && map[nx] == 0) {//滿足條件即加入隊列;
q.x = nx;
map[nx] = 1;//將該點標(biāo)為已經(jīng)訪問過;
q.step = p.step + 1;
que[r++] = q;
}
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
int s, e;
while (cin >> s >> e) {
int ans = bfs(s, e);
cout << ans << endl;
}
return 0;
}