HDU2717 Catch That Cow(简单BFS)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_42391248/article/details/82966443

Catch That Cow

Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 21112    Accepted Submission(s): 6127

Problem 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

题目大意:一条数轴上,给出一个初始位置和要到达的位置,每次可以+1,-1,*2操作,问最少几次操作能从起始位置到达最终位置。

具体代码如下:

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int N=100000+5;
bool map[N];
struct node{
	int x,time;
};
int k,n;
int check(int x)
{
	if(x>=N||map[x]==true||x<0)
		return 0;
	return 1;
}
int BFS()
{
	queue<node> q;
	node now,next;
	now.x=n;
	now.time=0;
	q.push(now);
	while(!q.empty())
	{
		now=q.front();
		q.pop();		
		if(now.x==k)
			return now.time;
		//1
		next.x=now.x+1;
		next.time=now.time+1;
		if(check(next.x))
		{
			q.push(next);
			map[next.x]=1;
		}	
		//2
		next.x=now.x-1;     
		next.time=now.time+1;        
		if(check(next.x))            
		{                
			q.push(next);                
			map[next.x]=1;          
	    }  
		//3  
		next.x=now.x*2;      
		next.time = now.time + 1;    
	    if(check(next.x))          
		{                
			q.push(next);               
			map[next.x]=1;          
		}
	}	
	return -1;
}
int main()
{
	int ans;
	while(cin>>n>>k)
	{
		memset(map,0,sizeof(map));
		ans=BFS();
		cout<<ans<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42391248/article/details/82966443