您的位置:首页 > 其它

POJ-3278 Catch That Cow 解题报告

2012-03-03 23:47 483 查看
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 X - 1 or X + 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
=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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: