标签:
Catch That Cow
Time Limit:2000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
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.
Input
Line 1: Two space-separated integers: N and K
Output
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 <stdio.h> 2 #include <string.h> 3 #include<queue> 4 5 using namespace std; 6 7 int vis[120000]; 8 int n,k,flag; 9 10 struct Node 11 { 12 int x; 13 int tm; 14 }root; 15 16 void bfs() 17 { 18 memset(vis,0,sizeof(vis)); 19 queue<Node>que; 20 que.push(root); 21 22 vis[root.x] = 1; 23 int ans=100005; 24 25 while(!que.empty()) 26 { 27 Node q = que.front(); 28 que.pop(); 29 30 //printf("q.x = %d\n",q.x); 31 32 if(q.x == k ) 33 { 34 ans = q.tm; 35 flag = 1; 36 break; 37 } 38 39 Node q1,q2,q3; 40 41 if(q.x+1 < 100005 &&!vis[q.x + 1] ) 42 { 43 //printf("q2.x = %d\n",q.x+1); 44 q2.x = q.x + 1; 45 q2.tm = q.tm + 1; 46 47 vis[q2.x] = 1; 48 que.push(q2); 49 } 50 51 if(q.x-1 >=0 && !vis[q.x - 1] ) 52 { 53 //printf("q1.x = %d\n",q.x-1); 54 q1.x = q.x - 1; 55 q1.tm = q.tm + 1; 56 57 vis[q1.x] = 1; 58 que.push(q1); 59 } 60 61 62 63 if(q.x *2 <100005 && !vis[q.x *2] ) 64 { 65 //printf("q3.x = %d\n",q.x*2); 66 q3.x = q.x *2; 67 q3.tm = q.tm + 1; 68 69 vis[q3.x] = 1; 70 que.push(q3); 71 72 } 73 } 74 if(flag) printf("%d\n",ans); 75 //else printf("-1\n"); 76 } 77 78 79 int main() 80 { 81 82 while(~scanf("%d%d",&n,&k)) 83 { 84 flag = 0; 85 86 root.x = n; 87 root.tm = 0; 88 89 bfs(); 90 } 91 92 return 0; 93 }
HDU2717 Catch That Cow ( BFS )
标签:
原文地址:http://www.cnblogs.com/GY8023/p/4682057.html