您的位置:首页 > 其它

抓住那头牛

2017-08-21 19:30 162 查看

抓住那头牛

查看
提交
统计
提问

总时间限制: 2000ms 内存限制: 65536kB
描述

农夫知道一头牛的位置,想要抓住它。农夫和牛都位于数轴上,农夫起始位于点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>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<iomanip>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>
using namespace std;
int n,k;
struct Node
{
int x,step;
Node(int xx,int ss)
{
x=xx;step=ss;
}
};
queue<Node>q;
bool tag[200005];
int main()
{
cin>>n>>k;
q.push(Node(n,0));
memset(tag,0,sizeof(tag));
tag
=true;
while(!q.empty())
{
Node tmp=q.front();
int x=tmp.x,s=tmp.step;
q.pop();
if(x==k)
{
cout<<s<<endl;
break;
}
if(x+1<=k&&!tag[x+1])
{
tag[x+1]=true;
q.push(Node(x+1,s+1));
}
if(x<k&&!tag[2*x])
{
tag[2*x]=true;
q.push(Node(2*x,s+1));
}
if(x-1>=0&&!tag[x-1])
{
tag[x-1]=true;
q.push(Node(x-1,s+1));
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: