http://acm.hdu.edu.cn/showproblem.php?pid=2717
Problem 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
题意分析:
一个人要找他的牛,当前位置为x,每次可以去的地方有x+1, x-1, x*2,求到达牛的位置需要多少步。
解题思路:
每次对当前位置BFS,下一步可能是x+1, x-1, x*2,已经走过的不用再走,注意数组越界。
#include <stdio.h>
#include <string.h>
#include <queue>
#define N 200020
using namespace std;
bool book[N];
struct date{
int x;
int temp;
};
int bfs(int s, int t)
{
int tx;
memset(book, false, sizeof(book));
queue<date>q;
book[s]=true;
q.push(date{s, 0});
while(!q.empty())
{
date u=q.front();
q.pop();
if(u.x==t)
return u.temp;
tx=u.x+1;
if(book[tx]==false && tx>=0 && tx<=t+2)
{
book[tx]=true;
q.push({tx, u.temp+1});
}
tx=u.x-1;
if(book[tx]==false && tx>=0 && tx<=t+2)
{
book[tx]=true;
q.push({tx, u.temp+1});
}
tx=u.x*2;
if(book[tx]==false && tx>=0 && tx<=t+2)
{
book[tx]=true;
q.push({tx, u.temp+1});
}
}
}
int main()
{
int n, k;
while(scanf("%d%d", &n, &k)!=EOF)
{
if(n>k)
printf("%d
", n-k);
else
printf("%d
", bfs(n, k));
}
return 0;
}