您的位置:首页 > 其它

POJ-3278-Catch That Cow

2017-09-19 21:16 330 查看
Description

Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number
line. Farmer John has two modes of transportation: walking and teleporting.

* Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute

* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

Input

Line 1: Two space-separated integers: N and K
Output

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Sample Input
5 17

Sample Output
4

Hint

The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.

这是一道简单的BFS题,只是将以前的4个方向变成两个方向就行。同时这里需要注意开vis数组的时候一定要开大些,不然会一直出现RE

代码如下:
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cstring>
typedef long long ll;
using namespace std;
ll maxn = 200005;
ll n,k;
ll vis[200005];
struct node
{
ll x,time;
};
bool check(ll x)
{
if(vis[x])
return true;
else if(x<0)
return true;
return false;
}
ll bfs()
{
node s,next;
s.x = n;
s.time = 0;
vis[s.x]=1;
queue<node>q;
q.push(s);
while(!q.empty())
{
s = q.front();
q.pop();
if(s.x==k)
return s.time;
for(int a = 0; a < 3; a ++)
{
next = s;
if(a==0)
next.x = s.x+1;
else if(a==1)
next.x = s.x-1;
else if(a==2&&s.x<k)
next.x = s.x*2;
if(check(next.x))
continue;
next.time = s.time+1;
vis[next.x]=1;
q.push(next);
}
}
return 0;
}
int main()
{
scanf("%lld%lld",&n,&k);
memset(vis,0,sizeof(vis));
ll ans = bfs();
printf("%lld",ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: