天天看點

Catch That Cow

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?

Line 1: Two space-separated integers: N and K

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

5 17

4

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.

從起點出發,随機挑一個方向,能往前走就往前走(擴充),走不動了則回溯。

不能走已經走過的點(要判重)。

要想求最優解,則要周遊所有走法。可以用各種手段優化,比如,若已經找到路徑長度為n的解,則所有大于n的走法就不必嘗試。

運算過程中需要存儲路徑上的節點,數量較少。用棧存節點。

給節點分層。起點是第0層。從起點最少需要n步就能到達的點屬于第n層。

依層次順序,從小到大擴充節點。把層次低的點全部擴充出來後,才會擴充層次高的點。

擴充時不能擴充已經走過的節點(要判重)。

可確定找到最優解,但是因擴充出來的節點較多,且多數節點都需要儲存,是以需要的存儲空間較大。用隊列存儲節點。