@xunuo
2017-04-16T17:38:30.000000Z
字数 1705
阅读 1024
Time Limit: 2000MS Memory Limit: 65536K
BFS
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?
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.
5 17
4
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.
题意:
有一个牧羊人和一头牛,人在x点,牛在y点,他们都在一条数轴上,牧羊人想要去抓牛,但是他一次只能走到x+1,x-1或者是2*x处;在抓牛的过程中牛不动,问你牧羊人最短要多长时间能够抓到牛,人跳一次花一分钟;
解题思路:
把每种情况都走一遍,谁最先到达谁就是最短的,走过了的就标记一下;
完整代码:
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
const int maxn=200000;////要开打两倍!!!估计是因为有2*x吧??!!。。
int vis[200010];
int ans;
struct node
{
int x;
int num;
};
int bfs(int st,int en)
{
queue<node>q;
node now,next;
now.x=st;
now.num=0;
vis[st]=1;
q.push(now);
while(!q.empty())
{
now=q.front();
q.pop();
if(now.x==en)
{
ans=now.num;
break;
}
next=now;
next.x=now.x+1;
if(next.x>=0&&next.x<maxn&&vis[next.x]==0)
{
next.num=now.num+1;
vis[next.x]=1;
q.push(next);
}
next.x=now.x-1;
if(next.x>=0&&next.x<maxn&&vis[next.x]==0)
{
next.num=now.num+1;
vis[next.x]=1;
q.push(next);
}
next.x=2*now.x;
if(next.x>=0&&next.x<maxn&&vis[next.x]==0)
{
next.num=now.num+1;
vis[next.x]=1;
q.push(next);
}
}
return ans;
}
int main()
{
int st,en;
while(scanf("%d%d",&st,&en)!=EOF)
{
memset(vis,0,sizeof(vis));
printf("%d\n", bfs(st,en));
}
return 0;
}