POJ-3278 Catch That Cow 解题报告

来源:互联网 发布:山航待遇怎么样知乎 编辑:程序博客网 时间:2024/05/27 20:17

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.

       题目链接:http://poj.org/problem?id=3278
       解法类型:BFS
       解题思路:直接用的BFS,为了减少入队列的情况,用一标记数组vis来储存已经经过的路径,然后还可以用一个判断来减少2*N如队列的情况,即k-n1>2*n1-k。但这样算下来,队列也要开到1100000的样子,这样memory用到了9000多KB,time也要63MS,算法的效率也就一般,但对这题来说可以直接水过了。看到那题的status,有人只用了8KB的内存,当场被吓了。这几天还是想个更好地算法吧。~
       算法实现:
//STATUS:C++_AC_63MS_9564K#include<stdio.h>#include<memory.h>int BFS();const int MAXN=1100100;int vis[200010],n,k,q[MAXN][2],d[2]={1,-1};int main(){//freopen("in.txt","r",stdin);while(scanf("%d%d",&n,&k)!=EOF){memset(q,0,sizeof(q));memset(vis,0,sizeof(vis));k<=n?printf("%d\n",n-k):printf("%d\n",BFS());}return 0;}int BFS(){int i,front=0,rear=0,n1,n2,t;q[rear++][0]=n;vis[n]=1;while(front<rear){n1=q[front][0];if(n1==k)return q[front][1];t=q[front++][1]+1;for(i=0;i<2;i++){n2=n1+d[i];if(!vis[n2]){    vis[n2]=1;  //vis    q[rear][0]=n2;     q[rear++][1]=t;}}if( k-n1>2*n1-k ){  //判断是否2*n的情况能否入队列n2=2*n1;if(!vis[n2]){vis[n2]=1;  //vis    q[rear][0]=n2;q[rear++][1]=t;}}}return 0;}