POJ3278 - Catch That Cow
文章目录
链接:https://vjudge.net/problem/POJ-3278
Task
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:
|
|
output:
|
|
Solution
每走到一个点x
,可有3种决策:-1,+1,*2,可根据此得到一棵决策树
,如下图。根节点为初始位置,度为3,每个节点中存储当前位置x
和当前深度step
。要找到最少步数,即是决策树生长停止时的最小深度。用广度优先搜索
。
用队列
实现BFS,初始时将根节点放入空队列,然后将队首节点取出,算出其3个子节点,将3个子节点分别入队(保证同深度的节点连续,这样取出时也是连续取出,即广度优先)。重复这个过程,直到某个节点的x等于目的K
过程中用一个数组location
来保证不走重复位置,避免陷入循环。
location=0和1分别是未走过和已经走过的位置。location的大小是允许走的最大长度。
这个最大长度是N,K取值范围[0,100000]的两倍,因为有时候需要走到K后面,再往回走。如K=100000,N=50001,则(x*2)->(x-1)->(x-1)是最短路径。
|
|