C - Catch That Cow 【kuangbin带你飞专题一】

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.

题意:给你两个数字n,m,有三个操作:1、当前数字减一;2、当前数字加一;3、当前数字乘二。目标是让n变成m。

总结:分两种情况来考虑。1、当n >= m 时,我们当前的操作唯有减一可以接近目标值m,想当然的想到结果为n-m的值。

2、当n<m时,我们三种操作都可以做,此时使用BFS来操作寻找最优解。但是考虑到解的结果为0~100000所以给每次加入队列的值设置加入条件。下面的源代码有个很弟弟的地方,就是没有体现出BFS的特点,即第一次找到的解即为最优解,所以是不需要反复判断rst取min的,直接break就完事儿了应该(人菜,想的还多  QAQ)。

#include<iostream>
#include<vector>
#include<stack>
#include<map>
#include<cstdio>
#include<queue>
#include<algorithm>
#include<cstdlib>
#include<cmath>
using namespace std;
#define ll long long
#define rep(i,n) for(int i = 0; i < n; i++)
const ll N = 3e5 + 200;
const ll INF = 0x3f3f3f;
const ll Mode = 1e9 + 7;
typedef struct{
	int first,second;
}node;
int use[N] = {0};
queue<node> q;
int main(){
	int n,k;
	cin>>n>>k;
	if(n >= k){
		cout<<n-k<<endl;
		exit(0);
	}
	int rst = k - n;
	node x;
	x.first = n;
	x.second = 0;
	q.push(x);
	while(!q.empty()){
		node p = q.front();
		q.pop();
		int t1 = p.first;
		int t2 = p.second;
		if(t2 < rst){
			if(t1 == k) rst = min(t2,rst);
			if(!use[t1+1] && t1+1 <= k){
				node tmp;
				tmp.first = t1+1;
				tmp.second = t2+1;
				q.push(tmp);
				use[t1+1] = 1;
			}
			if(t1-1 > 0 && !use[t1-1]){
				node tmp;
				tmp.first = t1-1;
				tmp.second = t2+1;
				q.push(tmp);
				use[t1-1] = 1;
			}
			if(!use[t1*2] && t1*2 <= 100000){
				node tmp;
				tmp.first = t1*2;
				tmp.second = t2+1;
				q.push(tmp);
				use[t1*2] = 1;
			}
		}
	}
	cout<<rst<<endl;
}

猜你喜欢

转载自blog.csdn.net/qq_41991981/article/details/97671631
今日推荐