poj 3278 Catch That Cow(大概是很显然的bfs了)

Catch That Cow

题目链接

Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 123882   Accepted: 38547

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

扫描二维码关注公众号,回复: 4337431 查看本文章
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和k,起点和终点的位置。每次移动需要1分钟,每次移动的方式有3种,+1、-1、×2,范围是0~100000,求最短需要用多长时间。

【分析】bfs。需要用一个vis数组,来记录该点是不是已经走过,避免重复。然后,向前或向后即±1存进一个数组里,再讨论×2。如果最初n和k相同的话,用时显然为0了。

【代码】

#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<queue>
using namespace std;

struct node{
	int x,step;
};

const int maxn=1e5+10;
int vis[maxn];
int dir[5]={-1,1};

int bfs(int n,int k)
{
	queue<node>q;
	node n1,n2,n3;
	n1.step=0,n1.x=n;
	q.push(n1);
	while(!q.empty())
	{
		n2=q.front();q.pop();
		if(n2.x==k) return n2.step;
		for(int i=0;i<2;i++)
		{
			n3.x=n2.x+dir[i];
			n3.step=n2.step+1;
			if(n3.x<0 || n3.x>100000)continue;//这里是x,不要写成step.... 
			if(vis[n3.x])continue;
			vis[n3.x]=1;
			q.push(n3); 
		}
		n3.x=n2.x*2;n3.step=n2.step+1;
		if(n3.x<0 || n3.x>100000)continue;
		if(vis[n3.x])continue;
		vis[n3.x]=1;
		q.push(n3); 		
	}
	return 0;
}

int main()
{
	int n,k;
	while(~scanf("%d%d",&n,&k))
	{
		if(n==k)
		{
			puts("0");
			continue;
		}
		memset(vis,0,sizeof(vis));
		printf("%d\n",bfs(n,k));
	}
	return 0;
}
 
 
 

猜你喜欢

转载自blog.csdn.net/qq_38735931/article/details/84197563
今日推荐