HUD3278 Catch That Cow(BFS)

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.

题目大意:给出起始位置与牛所在的位置,你只能进行2种操作:向前或向后移动一步,或者从当前位置到达2*n处。求到达目标位置的最小操作次数。

思路:以前写的时候总以为是DFS,然后各自WA 各种T。考虑最优操作,采用BFS队列处理。

代码如下:

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
#include<queue>
#include<set> 
#include<map>
#include<string>
using namespace std;
int f[2]={-1,1};
struct fun{
	int x;
	int t;
}p,p1;
int bfs(int x,int k)
{
	queue<fun>q1,q2;
	p.x=x;p.t=0;
	int vis[100005]={0};
	q1.push(p);
	while(!q1.empty())
	{
		p=q1.front();q1.pop(); 
	    if(p.x==k)
	    return p.t;
	    for(int i=0;i<2;i++)
	    {
	    	p1.x=p.x+f[i];
	    	p1.t=p.t+1;
	    	if(p1.x>=0&&p1.x<=100000&&vis[p1.x]==0)
	    	{
	    	    vis[p1.x]=1;
	    	    q1.push(p1);
		}
             }
	     p1.x=p.x*2;p1.t=p.t+1;
	     if(p1.x>=0&&p1.x<=100000&&vis[p1.x]==0)
	     {
		 vis[p1.x]=1;
		 q1.push(p1);
	     }
	}
	return 0;
}
int main()
{
	int n,m;
	scanf("%d%d",&n,&m);
	printf("%d\n",bfs(n,m));
	return 0;
}

猜你喜欢

转载自blog.csdn.net/pleasantly1/article/details/81019560