Crawling in process... Crawling failed Time Limit:2000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
Submit Status Practice POJ 3278Description
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 KOutput
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. 題目大意:農夫去追他跑丟的牛,題目給出了他和牛的位置,用數字N和K表示,假定牛不動,問農夫移動到牛的位置的最小步數,農夫每次的移動有三種選擇:位置加1,位置減1,位置乘2. 思路分析:求最小步數,用BFS即可水過,不過由於本弱BFS剛剛入門,在做題的時候還是出現了很多問題,BFS一般要采用隊列來進行實現,剛開始使用的是queue<int>隊列,但是在對步數的保存上出現了問題,這時候我選擇了queue<pair <int,int> >來記錄位置和步數,每次將n+1,n-1,n*2都壓入到隊列當中去,直到n==m,結束。程序可以運行,樣例的輸出答案也是正確的,但是提交的時候MLE了,這讓我明白了剪枝的重要性,最後程序在兩個方面進行了剪枝,一個是建立一個標記數組,對搜索到的每一點都進行標記,避免重復搜索,第二就是對於n>m的情況,毫無疑問應該采取n-1。應用了這兩點剪枝策略以後,成功A掉。 代碼:#include <iostream>