Catch That Cow
Time Limit : 4000/2000ms (Java/Other) Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 67 Accepted Submission(s) : 22
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
Source
PKU
题意:牛逃跑了,人要去抓回来这只牛,他们在一条直线上 ,现在牛的坐标是K,人的坐标是N,牛呆在原位置不动。人有两种行进方式,步行和传送,步行可以向前或向后走一步,传送为到达人当前坐标*2 的位置。每行进一次用一分钟,问人最少需要几分钟可以抓到牛。
思路:
代码:
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<queue> 5 6 using namespace std; 7 8 const int maxn=100000; 9 10 int vis[maxn+10]; 11 int n,k; 12 13 struct node 14 { 15 int x,c; 16 }; 17 18 int BFS() 19 { 20 queue<node> q; 21 while(!q.empty()) 22 q.pop(); 23 memset(vis,0,sizeof(vis)); 24 node cur,next; 25 cur.x=n,cur.c=0; 26 vis[cur.x]=1; 27 q.push(cur); 28 while(!q.empty()) 29 { 30 cur=q.front(); 31 q.pop(); 32 for(int i=0; i<3; i++) 33 { 34 if(i==0) 35 next.x=cur.x-1; 36 else if(i==1) 37 next.x=cur.x+1; 38 else 39 next.x=cur.x*2; 40 next.c=cur.c+1; 41 if(next.x==k) 42 return next.c; 43 if(next.x>=0 && next.x<=maxn && !vis[next.x]) 44 { 45 vis[next.x]=1; 46 q.push(next); 47 } 48 } 49 } 50 return 0; 51 } 52 53 int main() 54 { 55 56 freopen("1.txt","r",stdin); 57 58 while(~scanf("%d%d",&n,&k)) 59 { 60 if(n>=k) 61 { 62 printf("%d ",n-k); 63 continue; 64 } 65 printf("%d ",BFS()); 66 } 67 return 0; 68 }