Catch That Cow
Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 9276 Accepted Submission(s):
2907
Problem 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
题意:人在n位置处,牛在k位置处,牛不动问人最短多少分钟可以捉到牛,人有两种移动方法
1、一分钟移动一步n-1或者n+1
2、一分钟移动2*n步;
#include<stdio.h> #include<string.h> #include<queue> #define MAX 1000100 using namespace std; int n,m; int vis[MAX]; struct node { int x; int step; friend bool operator < (node a,node b) { return a.step>b.step; } }; int judge(int x) { if(x < 0||x > MAX||vis[x]) return 0; return 1; } void bfs(int n,int k) { int i,j; priority_queue<node>q; node beg,end; beg.x=n; beg.step=0; q.push(beg); vis[n]=1; while(!q.empty()) { beg=q.top(); q.pop(); if(beg.x==k) { printf("%d\n",beg.step); return ; } end.x=beg.x-1; if(judge(end.x)) { vis[end.x]=1; end.step=beg.step+1; q.push(end); } end.x=beg.x+1; if(judge(end.x)) { vis[end.x]=1; end.step=beg.step+1; q.push(end); } end.x=beg.x*2; if(judge(end.x)) { vis[end.x]=1; end.step=beg.step+1; q.push(end); } } } int main() { int i; while(scanf("%d%d",&n,&m)!=EOF) { memset(vis,0,sizeof(vis)); bfs(n,m); } return 0; }