C++广度优先搜索算法之抓住那头牛(Catch that cow)

抓住那头牛:

农夫知道一头牛的位置,想要抓住它。农夫和牛都位于数轴上,农夫起始位于点N(0<=N<=100000),牛位于点K(0<=K<=100000)。农夫有两种移动方式:

1、从X移动到X-1或X+1,每次移动花费一分钟

2、从X移动到2*X,每次移动花费一分钟

假设牛没有意识到农夫的行动,站在原地不动。农夫最少要花多少时间才能抓住牛?

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 pointN (0 ≤N ≤ 100,000) on a number line and the cow is at a pointK (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 pointX to the pointsX- 1 orX + 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?

以上是题目,具体输入输出如下:

输入

两个整数,N和K。

输出

一个整数,农夫抓到牛所要花费的最小分钟数。

样例输入 5 17 样例输出 4

代码如下:

#include
const int sb=1e6;
bool mark[sb+1];
int que[sb+1],pre[sb+1],n,k;
int next;
void print(int x)
{
	int num=0;
	while(pre[x])
	{
		num++;
		x=pre[x];
	}
	printf("%d",num);
}
void bfs()
{
	if(n==k){printf("0");return ;}
	int head=0,tail=1;
	que[1]=n;
	mark[n]=true;
	while(head!=tail)
	{
		head++;
		for(int i=0;i<3;i++)
		{
			switch(i)
			{
				case 0: next=que[head]+1;break;
				case 1: next=que[head]-1;break;
				case 2: next=que[head]*2;break;
			}
			if(next>=0&&next<=sb&&mark[next]!=true)
			{
				tail++;
				que[tail]=next;
				mark[next]=true;
				pre[tail]=head;
				if(next==k) 
				{
					print(tail);
					head=tail;
					break;
				}
			}
		}
	}
}
int main()
{
	scanf("%d%d",&n,&k);
	bfs();
}



 

你可能感兴趣的:(广度优先搜索,C++学习日志,搜索算法刷题集锦)