POJ 3278 Catch That Cow

题意:Farmer John在一条线上追牛,他位于N,牛位于K。每一分钟从当前位置X他有两种方式追:移动到X-1或X+1;移到2X。问追到牛花费的最小时间。

分析:算最短时间用宽度搜索。将Farmer John的每一分钟的移动看做一次状态的变换,每一状态包含他的当前位置坐标和到当前位置花费的时间。移动分为三个相似代码段,每次将所有能由当前位置到达的位置全部加入队列。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <vector>
 5 #include <queue>
 6 #include <cmath>
 7 #include <stack>
 8 #include <set>
 9 #include <map>
10 #include <algorithm>
11 using namespace std;
12 #define ll long long
13 #define inf 0x3f3f3f3f
14 int n,k;
15 bool v[100001];
16 struct node
17 {
18     int e,t;
19 };
20 int bfs()
21 {
22     int i,j;
23     node a,b;
24     queue<node> q;
25     a.e=n,a.t=0;
26     v[n]=1;
27     q.push(a);
28     while(!q.empty())
29     {
30         b=q.front();
31         q.pop();
32         if(b.e==k) return b.t;
33         a.e=b.e+1;
34         if(a.e>=0&&a.e<=100000&&!v[a.e])
35         {
36             a.t=b.t+1;
37             v[a.e]=1;
38             q.push(a);
39         }
40         a.e=b.e-1;
41         if(a.e>=0&&a.e<=100000&&!v[a.e])
42         {
43             a.t=b.t+1;
44             v[a.e]=1;
45             q.push(a);
46         }
47         a.e=b.e*2;
48         if(a.e>=0&&a.e<=100000&&!v[a.e])
49         {
50             a.t=b.t+1;
51             v[a.e]=1;
52             q.push(a);
53         }
54     }
55     return -1;//根据题意一定可以追到,但是不加此句会WA,应该是OJ的问题
56 }
57 int main()
58 {
59     int i,j;
60     while(~scanf("%d %d",&n,&k))
61     {
62         if(n>=k)//如果起始位置坐标大于牛的坐标则只能靠X-1一种操作追到
63             printf("%d\n",n-k);
64         else
65         {
66             memset(v,0,sizeof v);
67             printf("%d\n",bfs());
68         }
69     }
70     return 0;
71 }

 

posted @ 2016-10-17 22:43  Nautilus1s  阅读(110)  评论(0编辑  收藏  举报