分類:DFS,STL,作者:ACShiryu時間:2011-7-23地址:http://www.cnblogs.com/ACShiryu/archive/2011/07/23/2114978.htmlCatch That Cow
| Time Limit: 2000MS |
|
Memory Limit: 65536K |
| Total Submissions: 24419 |
|
Accepted: 7511 |
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
題目大意,就是給出a和b點的橫座標,求到a,b的最小行動次數,其中每次行動只能是下面兩種情況之一
- 向左或向右移動一步,即橫座標加1或者減1
- 橫座標變成原來的兩倍
對於題目給出的資料5 17 , 可以這樣進行行動 5 -> 10 -> 9 -> 18 -> 17 所以只需要四步就可以到達b
這題因為是求最小行動次數,故可以用BFS,調用STL裡面的隊列來實現。每次去隊首元素,如果到達了b點,輸出步子並結束搜尋,否則,行動步子+1,並分別將改點的橫座標+1,-1,×2操作後壓入隊列,一直到尋找到解。注意到當位置的橫座標超過了b點就應該再向右走,故此時應該對其橫座標只有-1操作,還要注意到橫座標為0的特殊情況,此處應該只進行+1行走
剛開始的時候把標記數組開小了,沒注意到×2可能會出現超過100,000的情況,提交時RE了一次,把數組改打就AC了
1 #include<iostream>
2 #include<cstdlib>
3 #include<cstdio>
4 #include<cstring>
5 #include<algorithm>
6 #include<cmath>
7 #include<queue>
8 using namespace std;
9 bool hash[400001]; //標記改點是否走過,如果為true則走過
10 int main()
11 {
12 int m , n ;
13 while(cin>> n >> m )
14 {
15 memset(hash,false,sizeof(hash));//初始化
16 pair<int ,int>p; //第一個代表橫座標,第二個代表走的步子
17 p.first=n;
18 p.second=0; //初始化p
19 hash[n]=true;
20 queue<pair<int ,int>>bfs;
21 bfs.push(p);
22 while(!bfs.empty())
23 {
24 p=bfs.front(); //取隊首元素
25
26 if(p.first==m)
27 {//此時說明找到了,則輸出,並結束搜尋
28 cout<<p.second<<endl;
29 break;
30 }
31
32 p.second++; //移動次數+1
33 pair<int ,int>q;
34
35 if(p.first<m)
36 {//如果改點在目標點的左邊
37 q=p;
38 q.first*=2; //×2操作
39 if(hash[q.first]==false&&q.first)
40 {//點沒訪問過,則從改點開始繼續搜尋
41 hash[q.first]=true;
42 bfs.push(q);
43 }
44
45 //下面搜尋同上,注釋略
46 q=p;
47 q.first+=1;
48 if(hash[q.first]==false)
49 {
50 hash[q.first]=true;
51 bfs.push(q);
52 }
53
54 }
55
56 if(p.first>0)
57 {
58 q=p;
59 q.first--;
60 if(hash[q.first]==false)
61 {
62 hash[q.first]=true;
63 bfs.push(q);
64 }
65 }
66 bfs.pop(); //隊首元素出隊列
67 }
68 }
69 return 0;
70 }