HDU - 2717 Catch That Cow

https://vjudge.net/problem/HDU-2717

相似题: HDU - 1548 A strange lift

HDU - 2717 Catch That Cow

题目

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.

分析

广搜

AC代码

#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
const int N=2e5+10;
int bk[N];
struct state{
	int x,step;	
}now,nt,old;
void bfs(int n,int k )
{
	old.x=n; old.step=0;
	
	memset(bk,0,sizeof bk);
	bk[n]=1;
	
	queue<state> q;
	q.push(old);
	int tp;
	while(q.size())
	{
		now=q.front(); q.pop();
		int f=0;
		for(int i=0;i<3;i++)
		{
			if(i==0)
				tp=now.x-1;
			else if(i==1)
				tp=now.x+1;
			else
				tp=now.x*2;
			if(bk[tp] || tp<0 || tp>100000) 
				continue;
			bk[tp]=1;
			nt.x=tp;
			nt.step=now.step+1;
			q.push(nt);
			
			if(nt.x==k)
			{
				f=1;
				break;
			}
		}
		if(f)
			break;
	}
	cout<<q.back().step<<endl; 
}
int main()
{
	int n,k;
	while(cin>>n>>k)
	{
		if(k<=n) cout<<n-k<<endl;
		else bfs(n,k);
			
	}
	return 0;
	
 } 

posted @ 2021-07-16 11:21  斯文~  阅读(18)  评论(0)    收藏  举报

你好!