1. 程式人生 > 實用技巧 >POJ-3278 Catch That Cow(BFS)

POJ-3278 Catch That Cow(BFS)

Catch That Cow
Time Limit:2000MS Memory Limit:65536K
Total Submissions:169075 Accepted:51762

Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a pointN(0 ≤N≤ 100,000) on a number line and the cow is at a pointK(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 pointXto the pointsX- 1 orX+ 1 in a single minute
* Teleporting: FJ can move from any pointXto the point 2 ×Xin 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
andK

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

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.

Source

USACO 2007 Open Silver
首先拿道這個題以為是數論,用二進位制搗鼓了半天依然沒有什麼發現 想到搜尋,DFS or BFS? DFS一般要整個遍歷一遍再求解 BFS更適合解決一些最值問題,在最壞情況下和DFS的複雜度一致,但是一般情況下最值按照BFS都更易求 所以遇到一些最值搜尋問題時可以考慮用BFS 變形的最短路應該看出來 無論BFS還是DFS都一定要注意標記已經走過的點!!!!! 這題在一些細節上還有待注意,比如說起止點可以是0,還有可以先乘到終止點後面再減回來
 1 #include <cstdio>
 2 #include <cstdlib>
 3 #include <cstring>
 4 #include <queue>
 5 #include <stack>
 6 #include <vector>
 7 #include <iostream>
 8 #include "algorithm"
 9 using namespace std;
10 const int MAX=100005;
11 int n,m,ans;
12 bool co[MAX];
13 struct num{
14     int x,y;
15 };
16 queue <num> q;
17 int main(){
18     freopen ("cow.in","r",stdin);
19     freopen ("cow.out","w",stdout);
20     int i,j;
21     scanf("%d%d",&n,&m);
22     memset(co,true,sizeof(co));
23     num a,b;a.x=n,a.y=0;
24     q.push(a);
25     co[a.x]=false;
26     while (!q.empty()){
27         a=q.front();q.pop();
28         if (a.x*2<MAX && co[a.x*2]){
29             b.x=a.x*2,b.y=a.y+1;
30             q.push(b);
31             co[b.x]=false;
32             if (b.x==m){ans=b.y;break;}
33         }
34         if (a.x+1<MAX && co[a.x+1]){
35             b.x=a.x+1,b.y=a.y+1;
36             q.push(b);
37             co[b.x]=false;
38             if (b.x==m){ans=b.y;break;}
39         }
40         if (a.x-1>=0 && co[a.x-1]){
41             b.x=a.x-1,b.y=a.y+1;
42             q.push(b);
43             co[b.x]=false;
44             if (b.x==m){ans=b.y;break;}
45         }
46     }
47     printf("%d",ans);
48     return 0;
49 }