ybt1253_抓住那头牛

ybt1253_抓住那头牛

时空限制    1000ms/64MB

【题目描述】

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

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

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

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

【输入】

两个整数,N和K。

【输出】

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

【输入样例】

5 17

【输出样例】

4

代码

#include<iostream>
using namespace std;
const int N = 100005;
const int dx[] = {-1,1};
int n,k,que[N][2];
bool used[N];

void bfs(){
	int head=0,tail=1;
	que[1][1]=n; que[1][0]=0;	//存放坐标 步数
	used[n] = true;	//此处已走
	while (head<tail){
		head++;
		int xx;
		for (int i=0; i<2; i++){	//方式1
			xx=que[head][1]+dx[i];
			if (xx>=0 && xx<N && !used[xx]){
				tail++;
				que[tail][1]=xx;
				que[tail][0]=que[head][0]+1;
				used[xx] = true;
				if (xx==k) { cout<<que[head][0]+1<<endl; return; }
			}
		}
		xx=2*que[head][1];	//方式2
		if (xx>=0 && xx<N && !used[xx]){
			tail++;
			que[tail][1]=xx;
			que[tail][0]=que[head][0]+1;
			used[xx] = true;
			if (xx==k) { cout<<que[head][0]+1<<endl; return; }
		}
	}
}

int main(){
	cin>>n>>k;
	if (n>=k) cout<<n-k<<endl;
	else bfs();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/WDAJSNHC/article/details/81558299