Catch That Cow 农夫找牛 北大poj3278

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.

题目大意:农夫被告知逃亡奶牛的文职,并希望能够立即抓住奶牛。他刚开始站在点N(0<= N <= 100000)上,母牛站在同一条线的点K上,农夫有两种交通方式:步行和传送。

  • 行走:可以在一分钟内从任一点X移动到X-1或X+1。
  • 传送:可以在一分钟内从任一点X移动到2X点。

如果母牛不知道有人要去追它,根本不动,那么农夫需多长时间找到他。

分析:即求找到奶牛的最短时间。已知农夫的状态可以用一个二元组来表示(n,t),其中n是农夫所在的位置,t是N到n所耗费时间。从当前状态到下一状态可以有三种状态(n-1,t+1),(n+1,t+1),(2*n,t+1)。目标状态是(K,最短时间)把每下一层状态用树来表示,则每一层的时间都是一样的,那么按照宽度优先搜索的方式查找,当查找到K时,时间必定是最短时间。

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>

using namespace std;

const int MAXN = 100010 ;

struct Status{  //状态二元组
	int n,t;    //分别表示现在的位置,以及走过的时间。
	Status(int n,int t):n(n),t(t) {} //构造函数 
};

bool visit[MAXN]; //来判断当前位置是否已经访问过,避免重复判断

int BFS(int n,int k){
	queue<Status> myQueue ;  //使用队列来进行宽度优先搜索
	myQueue.push(Status(n,0)); //当前状态入队。
	visit[n] = true;   //已经入队的位置就不会再重复入队。
	while(!myQueue.empty()){
		Status current = myQueue.front();//队列第一个元素
		myQueue.pop();//弹出
		if(current.n == k){
			return current.t;
		} 
		for(int i = 0 ; i < 3;i++){ //三个状态 之后均入队
			Status next(current.n,current.t+1);
			if(i == 0){
				next.n -= 1;
			}else if(i == 1){
				next.n += 1;
			}else{
				next.n *= 2;
			}
			if(next.n < 0 || next.n >= MAXN || visit[next.n]){
			continue;       //状态不合法,则不做操作。
			}
			myQueue.push(next);
			visit[next.n]  = true;
		}
		
	}
}

int main()
{
	int n,k;
	cin>>n>>k;
	memset(visit,false,sizeof(visit));  //初试化,cstring
	cout<<BFS(n,k)<<endl;
	return 0;
}

宽度优先搜序相关:
玛雅人的密码:牛客网

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值