C - Catch That Cow POJ - 3278
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?
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 17Sample Output
4Hint
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.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<set> 2 #include<map> 3 #include<cmath> 4 #include<queue> 5 #include<string> 6 #include<cstdio> 7 #include<cstring> 8 #include<sstream> 9 #include<cstdlib> 10 #include<cstring> 11 #include<sstream> 12 #include<iostream> 13 #include<algorithm> 14 15 using namespace std; 16 const int maxn = 100500; 17 const int INF = 0x3f3f3f3f; 18 const int mod = 7; 19 typedef long long ll; 20 #define PI 3.1415927 21 22 int n, k; 23 bool vis[maxn]; 24 int ans; 25 struct Node 26 { 27 int num; 28 int step; 29 Node(int _num, int _s){num=_num;step=_s;} 30 }; 31 void bfs() 32 { 33 queue<Node> que; 34 que.push(Node(n, 0)); 35 vis[n] = true; 36 while(que.size()) 37 { 38 Node nn = que.front(); que.pop(); 39 int nnum = nn.num+1; 40 if(0<=nnum&&nnum<maxn&&!vis[nnum]) 41 { 42 if(nnum == k) 43 { 44 ans = nn.step+1; 45 break; 46 } 47 que.push(Node(nnum, nn.step+1)); 48 vis[nnum] = true; 49 } 50 nnum = nn.num-1; 51 if(0<=nnum&&nnum<maxn&&!vis[nnum]) 52 { 53 if(nnum == k) 54 { 55 ans = nn.step+1; 56 break; 57 } 58 que.push(Node(nnum, nn.step+1)); 59 vis[nnum] = true; 60 } 61 nnum = nn.num*2; 62 if(0<=nnum&&nnum<maxn&&!vis[nnum]) 63 { 64 if(nnum == k) 65 { 66 ans = nn.step+1; 67 break; 68 } 69 que.push(Node(nnum, nn.step+1)); 70 vis[nnum] = true; 71 } 72 } 73 } 74 int main() 75 { 76 scanf("%d%d", &n, &k); 77 if(n<k) 78 { 79 bfs(); 80 printf("%d\n", ans); 81 } 82 else 83 { 84 printf("%d", n-k); 85 } 86 return 0; 87 }