Catch That Cow
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 122887 | Accepted: 38286 |
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.
http://poj.org/problem?id=3278
题意:
农夫想要去捉牛,给你农夫和牛的位置,牛的位置是不动的,例如农夫现在位置为5,农夫可以向前走+1走到6,也可以向后走-1走到4,还可以向前走到5*2=10。走一次花费1分钟,问你农夫捉到牛的最短时间。
思路:
如果牛在农夫的后面,那么农夫只能每次-1,所以最短时间为n-k。
其他情况:可以直接用bfs,来搜索,看到达牛的位置,用的最短时间。直接套模板。。。
代码:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int n, k;
int Min = -1;
bool book[100020];
struct node
{
int x;
int step;
};
bool check(node P)
{
if(P.x >= 0 && P.x <= 100020 && book[P.x] == false)
return true;
return false;
}
int bfs()
{
int move[3] = {1, -1, 1};
queue <node> q;
node s, now, next;
s.x = n;
s.step = 0;
book[s.x] = true;
q.push(s);
while(!q.empty())
{
now = q.front();
q.pop();
if(now.x == k) {
return now.step;
}
for(int i = 0; i < 3; i++) {
if(i != 2) {
next.x = now.x + move[i];
}
else {
next.x = now.x * 2;
}
next.step = now.step + 1;
if(check(next)) {
book[next.x] = true;
q.push(next);
if(next.x == k)
return next.step;
}
}
}
return 0;
}
int main()
{
memset(book, false, sizeof(book));
cin >> n >> k;
if(n >= k) {
cout << n - k << endl;
}
else {
cout << bfs() << endl;
}
return 0;
}