poj3278Catch That Cow 经典宽搜讲解

3278 Catch That Cow

Description

Farmer Johnhas been informed of the location of a fugitive cow and wants to catch herimmediately. He starts at a pointN (0 ≤ N ≤ 100,000) on a numberline and the cow is at a point K (0 ≤ K ≤ 100,000) on the samenumber line. Farmer John has two modes of transportation: walking andteleporting.

* Walking: FJcan move from any point X to the points X - 1 orX + 1 ina single minute
* Teleporting: FJ can move from any point X to the point 2 × X ina single minute.

If the cow,unaware of its pursuit, does not move at all, how long does it take for FarmerJohn to retrieve it?

Input

Line 1: Two space-separated integers: Nand K

Output

Line 1: The least amount of time, inminutes, 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 reachthe fugitive cow is to move along the following path: 5-10-9-18-17, which takes4 minutes.

 

大概题意:
 
Farmer John想抓到一头牛,Farmer John在一个数轴的一个位子,牛在数轴的另一个位子。但Farmer John这个人在一个单位时间内可以有三种走的方式,一是走到数轴的下一格,或是前一格,或是他的数轴的两倍的格子上,为此人最快抓到牛的时间。
 
解题思想:
其实是上面的一个变形,棋子变成了一个人和一头牛,然后走的规则变了一下,问的步数变成了时间。所以模板还是基本和上面的一样。
参考代码:
#include 
#include 
using namespace std;
int digit[200001];
int start,end;
int index;
bool find;
vectorvc;
void deal(int x,int time)
{
	if (x==end)
	{
		find=true;
		return;
	}
	if (x+1<=100000&&digit[x+1]==-1)
	{
		digit[x+1]=time+1;
		vc.push_back(x+1);
	}
	if (x-1>=0&&digit[x-1]==-1)
	{
		digit[x-1]=time+1;
		vc.push_back(x-1);
	}
	if (x*2<=200000&&digit[x*2]==-1)
	{
		digit[x*2]=time+1;
		vc.push_back(x*2);
	}
}
int main()
{
	cin>>start>>end;
	memset(digit,-1,sizeof(digit));
	vc.clear();
	vc.push_back(start);
	digit[start]=0;
	index=0;
	find=false;
	while (index	{
		deal(vc[index],digit[vc[index]]);
		index++;
	}
	cout<	return 0;
}

你可能感兴趣的:(poj,算法讲解)