POJ 3278 Catch That Cow (BFS + 隊列)

題目連接:http://poj.org/problem?id=3278ios


中文題意:農戶和牛在一個數軸上,農戶和牛的位置分別爲 n , k 。牛的位置不變,農戶有三種移動方式:1.從 n 移動到 n + 1。2.從 n 移動的 n - 1。3.從 n 變成 2 * n。且每種移動方式都須要花費一分鐘,問農戶最少須要多久能找到他的牛。數組

idea:典型 BFS + 隊列 的題,每次把三種移動方式的結果入隊(若是結果合法),記錄從上一步到這一步的步數便可。板子題,我還廢了這麼久,更加感受到本身的弱。ide

 1 #include <iostream>
 2 #include <cstdio>
 3 
 4 using namespace std;
 5 const int N = 1e5 + 10;
 6 int tt, ed, q[N], t[N];  // t[N]記錄步數,q[N]用數組模擬隊列 
 7 bool b[N];  //記錄當前位置是否出現過 
 8 
 9 void bfs(int o, int k)
10 {
11     q[ed ++ ] = o;
12     b[o] = true;
13     while (tt < ed)
14     {
15         int flag = 0;
16         for (int i = 0; i < 3; i ++ )
17         {
18             int temp;
19             if (!i)  temp = q[tt] + 1;
20             if (i == 1)  temp = q[tt] - 1;
21             if (i == 2)  temp = q[tt] * 2;
22             if (temp >= 0 && temp <= N)  //判斷步數是否合法 
23             {
24                 if (!b[temp])
25                 {
26                     t[ed] = t[tt] + 1;
27                     if (temp == k)
28                     {
29                         cout << t[ed] << endl;
30                         flag = 1;
31                         break;
32                     }
33                     q[ed ++ ] = temp;
34                     b[temp] = true;
35                 }
36             }
37         }
38         tt ++ ;
39         if (flag == 1)  break;
40     }
41 }
42 
43 int main()
44 {
45     int o, k;
46     cin >> o >> k;
47     if (o >= k)  cout << o - k << endl;  //若是 o >= k 農戶只能向後走 
48     else  bfs(o, k);
49     return 0;
50 }
View Code
相關文章
相關標籤/搜索