POJ - 3278 Catch That Cow(BFS)

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 - 1 or + 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.


思路:两种情况:1.人在牛右边,这种情况很明显,只能一次一次-1

                            2.人在牛左边,这边用bfs来做,只有三种情况(-1,+1,*2)。然后就可以了。

代码如下:

#include
#include
#include
using namespace std;

int f[100005];
struct node{
	int x;
	int step;
};

int  bfs(int l,int r){
	node st;
	node next;
	st.x=l;
	st.step=0;
	f[st.x]=1;
	queue q;
	q.push(st);
	while(!q.empty()){
		st=q.front();
		q.pop();
		for(int i=0;i<3;i++){
			if(i==0)
				next.x=st.x+1;
			else if(i==1)
				next.x=st.x-1;
			else if(i==2)
				next.x=st.x*2;
			//st.x+=next;
			if(next.x<0||next.x>=100010)
				continue;
			if(!f[next.x])
			{
				f[next.x]=1;
				next.step=st.step+1;
				q.push(next);
				if(next.x==r)
				return next.step;
			}
			
			
			}
		} 
	
}

int main(){
	int n,k;
	while(~scanf("%d%d",&n,&k)){
		memset(f,0,sizeof(f));
		if(n>=k)
			printf("%d\n",n-k);
		else
			printf("%d\n",bfs(n,k));
	}
	return 0;
}

你可能感兴趣的:(搜索)