Problem Description Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. 农民J 被告知 fugitive牛的定位,并且想立马逮到他! 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. 他在一个点N上开始走,牛在K上, Farmer John has two modes of transportation: walking and teleporting. 交通:走/电运 走路:一分钟走到 x-1 x+1 多次时间抓到? 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. |
#include <iostream>
#include <queue>
using namespace std;
typedef struct Now {
int pos;
int t;
} Now;
bool mark[100001];
queue<Now> q;
int bfs(int n,int k) {
while(!q.empty()) {
q.pop();
}
Now chu;
chu.pos = n;
chu.t = 0;
Now father;
Now child;
q.push(chu);
while(!q.empty()) {
father = q.front();
q.pop();
if (father.pos + 1 >= 0 && father.pos + 1 <= 100000 && mark[father.pos + 1] == 0) {
child = father;
child.pos ++;
child.t++;
if (child.pos == k) {
return child.t;
}
mark[child.pos] = 1;
q.push(child);
}
if (father.pos - 1 >= 0 && father.pos - 1 <= 100000 && mark[father.pos - 1] == 0) {
child = father;
child.pos --;
child.t++;
if (child.pos == k) {
return child.t;
}
mark[child.pos] = 1;
q.push(child);
}
if (father.pos * 2 >= 0 && father.pos * 2 <= 100000 && mark[father.pos * 2] == 0) {
child = father;
child.pos *= 2;
child.t++;
if (child.pos == k) {
return child.t;
}
mark[child.pos] = 1;
q.push(child);
}
}
return -1;
}
int main() {
int n;
int k;
while (cin >> n >> k) {
for (int i = 0; i <= 100000; i++) {
mark[i] = 0;
}
if (n == k) {
cout << 0 << endl;
} else {
int res = bfs(n,k);
cout << res << endl;
}
}
}