POJ 3278 Catch That Cow (宽搜)

题目链接:POJ 3278

Describe:

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

题目大意:

FJ和他的牛在一个数轴上,牛不动,FJ每次可以向前一步,或者向后一步,或者跳到当前坐标2倍的位置,问他最少走多少步可以抓到他的牛。

解题思路:

BFS,将每种情况入队,直到找到牛,用dfs会超时。

AC代码:

 

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <queue>
 4 using namespace std;
 5 int x,y,ans,f[200000],p[200000];  // 表示数轴,开两倍大小,p表示走到当前位置时的步数
 6 int main()
 7 {
 8     scanf("%d%d",&x,&y);
 9     ans = -1;
10     queue<int> q;
11     q.push(x); // 起始位置入队
12     while(!q.empty())
13     {
14         int tmp,t = q.front(); q.pop();
15         if(t == y) {ans = p[t]; break;}
16         for(int i = 0; i < 3; i++) // 枚举三种情况
17         {
18             if(i == 0) tmp = t-1;
19             else if(i == 1) tmp = t+1;
20             else if(i == 2) tmp = t*2;
21             if(tmp < 0 || tmp > 200000) continue;
22             if(f[tmp] == 0) // 若该点没有走过
23             {
24                 f[tmp] = 1; // 标记已经走过
25                 p[tmp] = p[t]+1;
26                 q.push(tmp);
27             }
28         }
29     }
30     printf("%d",ans);
31     return 0;
32 }

 

小结:

搜索时,要注意不能重复走相同的路。

 

posted @ 2020-09-01 09:25  不敢说的梦  阅读(157)  评论(0)    收藏  举报