永夜初晗凝碧天

本博客现已全部转移到新地址,欲获取更多精彩文章,请访问http://acshiryu.github.io/

导航

POJ3278 Catch That Cow 解题报告

分类:DFS,STL,
作者:ACShiryu
时间:2011-7-23
Catch 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 - 1 or + 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 }

  

posted on 2011-07-23 17:22  ACShiryu  阅读(1525)  评论(0编辑  收藏  举报