[POJ_3278]Catch That Cow

来源:互联网 发布:中文翻译拼音拍摄软件 编辑:程序博客网 时间:2024/06/08 07:09

Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 58049 Accepted: 18049

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

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.

题意 :
1.已知起点位置N和终点位置K
2.已知起点运动的规律以及终点固定
3.求从N出发到K的最小时间

思路:
题目为BFS(广度优先算法)的典型应用,使用BFS方法逐步计算各种可能性,当起点运动位置到达终点时,完成便利,返回需要时间

代码如下:
#include <stdio.h>#define Max 1000000int que[Max+1];       //代表位置int time[Max+1];      //代表经过时间int n, k;bool isPass(int pos){if(pos > 0 && pos < Max+1 && !time[pos]) return true;else return false;};int CatchTheCow(){int rear = 0, front = 0;int cur,next;if(n >= k)return (n-k);que[rear ++] = n;while(front <= rear){cur = que[front ++];if(cur == k) return (time[cur]);for(int i = 0; i < 3; i++){if(i == 0)next = cur - 1;else if(i == 1)next = cur + 1;else next = cur*2;if(isPass(next)){time[next] = time[cur] + 1;que[rear ++] = next;}}}}int main(void){while(scanf("%d%d",&n,&k) != EOF){for(int i=0; i <= Max+1; i++)time[i] = 0;printf("%d\n", CatchTheCow());}return 0;}






0 0
原创粉丝点击