poj 3278--- Catch That Cow

A - Catch That Cow
Time Limit:2000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

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 - 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.



大致题意:FJ要去抓奶牛,他在n点,奶牛在k点,FJ每次可以选择:

   1.  前进一步  花费1分钟;

   2. 后退一步  花费1分钟;

   3.前进当前点X的2倍步,即2×X,花费1分钟;

问最少需要多少分钟他能抓到奶牛。


典型搜索题,但是数据量太大,不能用深搜,只能用广搜。

搜索三个步骤。


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
#define N 100005
using namespace std;
typedef struct Que{
	int num;
	int step;
}que; 
bool book[N];
queue<que> q;
void clear(queue<que> queue){
	while(!queue.empty()) queue.pop();
}
int main(int argc, char *argv[]) {
	int n,k,flag,ans;
	cin>>n>>k;
	//while(cin>>n>>k){
		clear(q);
		ans = 0;
		flag = 0;
		memset(book,0,sizeof(book));
	    if(n >= k) cout<<n-k<<endl;
	    else{
	    	book[n] = true;
		    que tmpn;
		    tmpn.num = n;
		    tmpn.step = 0;
		    q.push(tmpn);
		    while(!q.empty()){
		    	for(int cao = 1; cao <= 3; ++cao){
		    		que tn;
					switch(cao){
		    			case 1:
		    				tn.num = q.front().num + 1;
							break;
		    			case 2:
		    				tn.num = q.front().num - 1;
							break;
		    			case 3:
		    				tn.num = q.front().num * 2;
							break;
		    		}
		    		if(tn.num > N || tn.num < 0 || book[tn.num]) continue;
		    		if(!book[tn.num]){
		    			tn.step = q.front().step + 1;
						q.push(tn);
		    			book[tn.num] = true;
		    		} 
		    		if(q.back().num == k){
		    			ans = q.back().step;
		    			flag = 1;
		    			break;
		    		}
		    	}
		    	if(flag) break;
		    	q.pop();
		    }
		    cout<<ans<<endl;
	    }
	//}
	return 0;
}




猜你喜欢

转载自blog.csdn.net/shengsikandan/article/details/50907269