版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaohaibo_/article/details/85010023
写在开头:
可能是我对题目的理解有误,但我认为本题的测试数据实在是坑:
- 测试数据有多组,而不是单组
- 数据范围实际超过100000,数组需要开到500000
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.
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
#include <queue>
#include <map>
#define INF 0x3f3f3f3f
using namespace std;
struct node{
int pos;
int step;
node(){}
node(int pos,int step):pos(pos),step(step){}
};
const int maxn = 500050;
int book[maxn];
int k,n;
int Min = INF;
int bfs(){
node head, tail;
queue<node>que;
que.push(node(n, 0));
book[n] = 1;
while(!que.empty()){
head = que.front();
que.pop();
if(!book[head.pos + 1] && head.pos < 100000){
if(head.pos + 1 == k) return head.step + 1;
book[head.pos + 1] = 1;
que.push(node(head.pos + 1, head.step + 1));
}
if(!book[head.pos - 1] && head.pos > 0){
if(head.pos - 1 == k) return head.step + 1;
book[head.pos - 1] = 1;
que.push(node(head.pos - 1, head.step + 1));
}
if(!book[head.pos << 1] && head.pos < 100000){
if(head.pos << 1 == k) return head.step + 1;
book[head.pos << 1] = 1;
que.push(node(head.pos << 1, head.step + 1));
}
}
return 0;
}
int main(){
ios::sync_with_stdio(false);
while(cin >> n >> k){
memset(book, 0, sizeof book);
cout << bfs() << endl;
}
return 0;
}