首页 > 代码库 > Catch That Cow
Catch That Cow
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.
1 #include <iostream> 2 #include <queue> 3 using namespace std; 4 5 struct node{ 6 int loc, step;//loc 当前位置, step 次数 7 }pos,q; 8 9 queue<node> que; 10 int vis[200005]; 11 12 void Push(int loc, int step){ 13 q.loc = loc; 14 q.step = step + 1; 15 vis[loc] = 1; 16 que.push(q); 17 } 18 19 int bfs(int n, int k){ 20 pos.loc = n, pos.step = 0; 21 vis[n] = 1; 22 que.push(pos); 23 while(!que.empty()){ 24 pos = que.front(); 25 que.pop(); 26 if(pos.loc == k) 27 return pos.step; 28 int loc_mov = pos.loc - 1; 29 if(loc_mov >= 0 && loc_mov < 200005 && vis[loc_mov] == 0){ 30 Push(loc_mov, pos.step); 31 } 32 loc_mov = pos.loc + 1; 33 if(loc_mov >= 0 && loc_mov < 200005 && vis[loc_mov] == 0){ 34 Push(loc_mov, pos.step); 35 } 36 loc_mov = 2 * pos.loc; 37 if(loc_mov >= 0 && loc_mov < 200005 && vis[loc_mov] == 0){ 38 Push(loc_mov, pos.step); 39 } 40 } 41 return -1; 42 } 43 44 int main(){ 45 int n, k; 46 cin >> n >> k; 47 cout << bfs(n, k) << endl; 48 }
Catch That Cow
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。