Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 100475 | Accepted: 31438 |
Description
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a pointN (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 orX + 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 andK
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.
Source
问题链接:POJ3278 HDU2717 Catch That Cow
题意简述:
一条线上,人的FJ的起点为K位置,牛在N位置(牛不动),输入正整数K和N。若FJ在x位置,FJ有三种走法,分别是走到x-1、x+1或2x位置。求从K走到N的最少步数。
问题分析:
典型的BFS问题。在BFS搜索过程中,走过的点就不必再走了,因为这次再走下去不可能比上次的步数少。
程序说明:
程序中,使用了一个队列来存放中间节点。
需要说明的是,除了BFS方法,这个题应该可以用分支限界法来解,需要更高的技巧。
AC的C++语言程序如下:
/* POJ3278 HDU2717 Catch That Cow */
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int MAXN = 100000;
const int MAXN2 = MAXN * 2;
bool notvist[MAXN * 2 + 2];
int n, k, ans;
struct node {
int p, level;
};
node start;
void bfs()
{
queue<node> q;
int nextp;
memset(notvist, true, sizeof(notvist));
notvist[n] = false;
start.p = n;
start.level = 0;
ans = 0;
q.push(start);
while(!q.empty()) {
node front = q.front();
q.pop();
if(front.p == k) {
ans = front.level;
break;
}
nextp = front.p - 1; /* x-1 */
if(nextp >= 0 && notvist[nextp]) {
notvist[nextp] = false;
node v;
v.p = nextp;
v.level = front.level + 1;
q.push(v);
}
nextp = front.p + 1; /* x+1 */
if(nextp <= MAXN2 && notvist[nextp]) {
notvist[nextp] = false;
node v;
v.p = nextp;
v.level = front.level + 1;
q.push(v);
}
nextp = front.p + front.p; /* 2x */
if(nextp <= MAXN2 && notvist[nextp]) {
notvist[nextp] = false;
node v;
v.p = nextp;
v.level = front.level + 1;
q.push(v);
}
}
}
int main()
{
while(cin >> n >> k) {
bfs();
printf("%d\n", ans);
}
return 0;
}