天天看点

[ACM] hdu 2717 Catch That Cow (BFS) Catch That Cow

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

Sample Output

Source

解题思路:

从位置n到位置k根据规则最少走几步可以到达,规则是从n可以走到n-1,可以走到n+1,也可以走到n*2.用bfs广搜来做,vis[]用来记录是否访问,hash[]用来记录走的步数。

遇到的问题有数组越界,一定要先判断n*2,n-1,n+1是否越界,还有问题就是步数的保存,因为很多节点都是同一个步数下的状态,因为每一步根据规则可以衍生出三种状态。所以用hash[ q.front() 下一个状态]=hash[q.front()]+1.用这种方法来记录步数,最后直接输出hash[k]就可以了。

代码: