Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 76935 | Accepted: 24323 |
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
Output
Sample Input
5 17
Sample Output
4
Hint
1 #include <iostream> 2 #include <string.h> 3 #include <queue> 4 #define MAXN 200000+10 5 using namespace std; 6 7 struct Node //***用结构体表示节点,x表示当前值,step记录当前步数 8 { 9 int x, step; 10 }; 11 12 int star, end, vis[MAXN]; 13 14 int bfs(int x) 15 { 16 Node a, b, c; 17 a.x = x, a.step = 0; //***赋初值 18 queue<Node>q; //***用队列实现 19 q.push(a); //***头节点入队 20 while(!q.empty()) //***如果队列不为空,继续循环 21 { 22 b = q.front(); //***取当前队列的头节点做父节点并将其从队列中删除 23 q.pop(); 24 vis[b.x] = 1; //***标记 25 if(b.x == end) //***如果达到目标,返回步数 26 { 27 return b.step; 28 } 29 c = b; //***符合条件的儿子入队 30 if(c.x >= 1 && !vis[c.x-1]) 31 { 32 c.x-=1; 33 c.step++; 34 vis[c.x]=1; 35 q.push(c); 36 } 37 c = b; 38 if(c.x < end && !vis[c.x+1]) 39 { 40 c.x+=1; 41 c.step++; 42 vis[c.x]=1; 43 q.push(c); 44 } 45 c = b; 46 if(c.x < end && !vis[2*c.x]) 47 { 48 c.x*=2; 49 c.step++; 50 vis[c.x]=1; 51 q.push(c); 52 } 53 } 54 return -1; 55 } 56 57 int main(void) 58 { 59 while(cin >> star >> end) 60 { 61 if(star >= end) //***如果star>=end,则每次减1,最少需要star-end步 62 { 63 cout << star - end << endl; 64 continue; 65 } 66 memset(vis, 0, sizeof(vis)); //***标记数组清0,不然会对后面的测试产生影响 67 int ans=bfs(star); //***深搜 68 cout << ans << endl; 69 } 70 return 0; 71 }