抓住那头奶牛
(catch that cow)
题目描述 Description
农夫约翰被告知一头逃跑奶牛的位置,想要立即抓住它,他开始在数轴的N 点(0≤N≤100000),奶牛在同一个数轴的K 点(0≤K≤100000)。约翰有两种移动方式:1 分钟内从x 点移动到x+1 或x-1;1 分钟内从x 点移动到2x。假设奶牛不会移动,约翰抓住它需要多少时间?
输入描述 Input Description
一行两个整数N 和K,用空格隔开。
输出描述 Output Description
约翰抓住它需要的最少时间。
样例输入 Sample Input
5 17
样例输出 Sample Output
【思路】4
很裸的一个广搜题目,每次通过一个循环将其节点拓展,注意Hash判重即可
code:
#include <iostream>
using namespace std;
#include <cstdlib>
#include <queue>
#include <cstring>
const int maxn=1000001;
queue<int>open;
int step[maxn];
int s,e,ans=1;
bool hash[maxn];
void init(){
cin>>s>>e;
if(s>e){cout<<s-e;exit(0);}//判断s<e的特殊情况
memset(hash,false,sizeof(hash));//初始化Hash表
open.push(s);//将初始节点压入队列
hash[s]=true;//将队列判重
}
void bfs(){
int i=0,next=0,head=0;
while(!open.empty()){
head=open.front();//需找队头
open.pop();//出队
for(i=0;i<3;i++){//循环找节点
if(i==0)next=head-1;
if(i==1)next=head+1;
if(i==2)next=head*2;
if(next>maxn || next<0)continue;//判断越界
if(hash[next]==false){//判重
open.push(next);
step[next]=step[head]+1;//更新路径数目
hash[next]=true;
}
if(next==e){cout<<step[next];return;}//如果已经到达目标节点,则结束
}
}
}
int main(){
init();
bfs();
return 0;
}