您的位置:首页 > 其它

POJ--3278 Catch That Cow

2015-08-06 17:17 302 查看
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
题意:额,大概意思就是农场主要去找他自己的牛,农场主在N行,牛在K行,农场主一次可以走+1,-1和2*N这三种行进路线,每一种都会花费1分钟,那么问题来了,农场主最快要几分钟能够捉到自己的牛。
注意:要注意特殊数据的考虑 比如0-100000或者100000-0一道比较正常的广搜。
ac代码:
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
#define INF 0xfffffff
int vis[100010];
int k,n,cn[2]={1,-1},ans;
struct node{
	int n,step;
}a,temp;
int jud(int x){
	if(x>=0&&x<=100000&&vis[x]==0)
		return 1;
	return 0;
}
void bfs(int x){
	queue<node>q;
		a.n=x;
		a.step=0;
	q.push(a);
	vis[a.n]=1;
	int i;
	while(!q.empty()){
		a=q.front();
		q.pop();
		for(i=0;i<3;i++){
			if(i==2)
				temp.n=a.n*2;
			else
				temp.n=a.n+cn[i];
			temp.step=a.step+1;
			if(jud(temp.n)){
				vis[temp.n]=1;
				if(temp.n==k){
				if(ans>temp.step)
					ans=temp.step;	
				continue ;
				}	
				q.push(temp);
			}
		
		}
	}

}

int main(){
	while(scanf("%d%d",&n,&k)!=EOF){
		memset(vis,0,sizeof(vis));
		ans=INF;
		if(n>=k)
			printf("%d\n",n-k);
		else{
			bfs(n);
			printf("%d\n",ans);	
		}
			
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: