Catch The Cow
Time limit 2000 ms
Memory limit 65536 kB
OS Linux
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.
农夫约翰已被告知逃亡牛的位置,并希望立即抓住它。他开始于一个点N(0≤ N ≤100,000)上的某条线,牛是在点K(0≤ K≤100,000)与点N在同一条线上。农夫约翰有两种交通方式:步行和传送。
- 行走:农夫约翰可以在一分钟内从任意点X移动到X -1或X + 1 点
- 传送:农夫约翰可以在一分钟内从任意点X移动到2× X点
如果母牛不知道农夫约翰在追它,根本不动,那么农夫约翰需要多长时间才能找回它?
- 输入`
第1行:两个以空格分隔的整数:N和K.
- 输出
第1行:Farmer John捕捉逃亡牛所需的最短时间(以分钟为单位)。
- 样例输入
5 17
- 样例输出
4
- 提示
农夫约翰到达逃亡牛的最快方法是沿着以下路径前进:5-10-9-18-17,这需要4分钟。
我一开始用暴力显然超时le
用BFS和队列写
然后输入有很多组…我被它的第一行蒙蔽了双眼
说起来POJ不支持万能头文件好气哦
这里是一个为了STL库写了半像不像C++的菜鸡_(:з」∠)_
Time 188ms
Memory 1216kB
Length 919
Lang C++
#include<iostream>
#include <cstdio>
#include <queue>
#include <cstring>
int f[100005];/*记录是否到过该位置*/
using namespace std;
int bfs(int x,int y){
int num, mins;
queue<int>q;
q.push(x);
q.push(0);/*压入位置点和时间*/
while(!q.empty()) {
num = q.front();
q.pop();
mins = q.front();
q.pop();
if(num == y) return mins;
else {
if(num - 1 >= 0 && !f[num - 1]) {
f[num - 1] = 1;
q.push(num - 1);
q.push(mins + 1);
}
if(num * 2 <= 100005 && !f[num * 2]) {
f[num * 2] = 1;
q.push(num * 2);
q.push(mins + 1);
}
if(num + 1 <= y && !f[num + 1]) {
f[num + 1] = 1;
q.push(num + 1);
q.push(mins + 1);
}
}
}
}
int main() {
int n, k;
while(~scanf("%d %d", &n, &k)) {
memset(f, 0, sizeof(f));
cout << bfs(n, k) << endl;
}
return 0;
}