Catch That Cow
Time Limit: 5000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8616 Accepted Submission(s): 2714
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?
* 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,常规思路。
注意:
题目所给5 17和17 5答案是不一样的。我曾天真地认为需要进行一步swap,实际上是不需要的。
遍历到某点应判断是否越界,否则也会ACCESS_VIOLATION。
数组也要开大一点,否则也会ACCESS_VIOLATION。
(PS:我忘记修改判断是否越界时界限的大小。)
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 using namespace std; 6 int vis[200010]; 7 int stp[200010]; 8 int n, k; 9 10 void swap(int& a, int& b) 11 { 12 a = a ^ b; 13 b = a ^ b; 14 a = a ^ b; 15 } 16 17 /* 18 int move(int sgn, int cur) 19 { 20 if(sgn == 1) 21 { 22 return cur + 1; 23 } 24 if(sgn == -1) 25 { 26 return cur - 1; 27 } 28 else 29 { 30 return cur * 2; 31 } 32 } 33 */ 34 35 void BFS(int ini) 36 { 37 int cur, now = 0; //init 38 queue<int> q; 39 vis[ini] = 1; 40 stp[ini] = 0; 41 q.push(ini); 42 while(!q.empty()) 43 { 44 cur = q.front(); 45 q.pop(); 46 for(int i = 0; i < 3; i++) 47 { 48 if(i == 0) 49 { 50 now = cur + 1; 51 } 52 else if(i == 1) 53 { 54 now = cur - 1; 55 } 56 else 57 { 58 now = cur * 2; 59 } 60 61 if(!vis[now] && now >= 0 && now <= 100010) 62 { 63 vis[now] = 1; 64 q.push(now); 65 stp[now] = stp[cur] + 1; 66 } 67 if(now == k) 68 { 69 printf("%d ", stp[now]); 70 return ; 71 } 72 } 73 } 74 } 75 int main() 76 { 77 while(scanf("%d %d", &n, &k) != EOF && n+k) 78 { 79 memset(vis, 0, sizeof(vis)); 80 memset(stp, 0, sizeof(stp)); 81 if (n == k) 82 { 83 printf("0 "); 84 } 85 else 86 { 87 BFS(n); 88 } 89 } 90 return 0; 91 }