例:
Sample Input
5 17
Sample Output
4
思路:
例子分析,农夫使用最短时间抓住牛的方案如下: 5-10-9-18-17, 需要4分钟。最短路径,用BFS。就像推格子一样,有一个现在的,有一个将来的,将现在的存进现在的结构体,同时运行三种情况比较其可行性并且时间最短。这个运算有范围限制。大于0且小于牛位置加2.主要在于BFS以及结构体的运用。
代码如下:
#include"stdio.h"
#include"cstring"
#include"algorithm"
#include"iostream"
#include"queue"
using namespace std;
int vst[100005];
int n,k;
struct wz
{
int x;
int time;
};
bool cheak(wz a)
{
if(a.x<0||a.x>k+2||vst[a.x] == 1)
{
return 0;
}
else
{
return 1;
}
}
void bfs(wz a)
{
queue q;
wz now,next;
a.time=0;
q.push(a);
vst[a.x]=1;
while(!q.empty())
{
now = q.front();
q.pop();
if(now.x==k)
{
cout<<now.time<<endl;
return;
}
next.x=now.x-1;
if(cheak(next))
{
next.time=now.time+1;
vst[next.x]=1;
q.push(next);
}
next.x=now.x+1;
if(cheak(next))
{
next.time=now.time+1;
vst[next.x]=1;
q.push(next);
}
next.x=now.x*2;
if(cheak(next))
{
next.time=now.time+1;
vst[next.x]=1;
q.push(next);
}
}
return;
}
int main()
{
while(cin>>n>>k)
{
if(n>k)
{
cout<<n-k<<endl;
}
wz a;
a.x=n;
memset(vst,0,sizeof(vst));
bfs(a);
}
return 0;
}
农夫和牛
最新推荐文章于 2023-09-24 09:28:30 发布