zufeoj_抓住那头牛

题目链接:http://acm.ocrosoft.com/problem.php?cid=1222&pid=21

题目描述

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

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

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

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

输入

两个整数,N和K。

输出

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

样例输入

5 17

样例输出

4

//BFS,三种状态搜索,记录下每到一个点走过的step,遍历所有点即可。

#include<bits/stdc++.h>
using namespace std;
const int inf=999999;
bool vis[inf];
int n,k;
int step[inf];
void bfs(){
	queue<int>q;
	int now,nextt;
	q.push(n);
	step[n]=0;
	vis[n]=1;
	while(!q.empty()){
		now=q.front();
		q.pop();
		for(int i=0;i<3;i++){
			if(i==0){
				nextt=now-1;
			}else if(i==1){
				nextt=now+1;
			}else{
				nextt=now*2;
			}
			if(nextt>inf||nextt<0){
				continue;
			}
			if(!vis[nextt]){
				q.push(nextt);
				step[nextt]=step[now]+1;
				vis[nextt]=1;
			}
			if(nextt==k){
				cout<<step[nextt]<<endl;
				return;
			}
		}
	}
}
int main(){
	memset(vis,0,sizeof(vis));
	cin>>n>>k;
	if(n>=k){
		cout<<n-k<<endl;
	}else{
		bfs();
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37345402/article/details/80982381
今日推荐