This is a good example of practice breadth-first search , which is often used in many wide-search teaching, and is placed here for learning the search algorithm of children's paper to see =
The main topic: on the one-dimensional axis, the farmer at N Point, the cow at the K point, assuming that the cow will not move, the farmer to find this cow can only carry out the following three methods of movement
- 2*n-jumps twice to his place.
- N+1-Move Right One
- N-1-Move left one
BFS Solution Resolution: Follow the steps to move the team first , pop off, and expand the next step to all the position and sequentially pressed into the queue (do not understand the child paper to find Niang, very basic data structure), here for code convenience, I use the STL queue.
Code is as follows:
1 //from N to K2 //either n*2 or N+1 or N-1.3 //time:94 Ms4#include <iostream>5#include <cstring>6#include <cstdio>7#include <queue>8 using namespacestd;9 Const intmaxn=100005;Ten intN,k;//Location , need to reach the location (one-dimensional) One intTIME[MAXN]; A intV[MAXN]; - voidBFS () - { the intcur,temp; -queue<int>Q; - Q.push (n); - while( !q.empty ()) + { -Cur =Q.front (); + Q.pop (); AV[cur] =1; at if(cur = =k) - { -cout<<time[cur]<<Endl; - return; - } - in for(intI=1; i<=3; i++) - { to if(i = =1) +temp = cur+1; - Else if(i = =2) thetemp = cur-1; * Else if(i = =3) $temp = cur*2;Panax Notoginseng //determine the range of temp first, lest v[] array out of bounds, ps:temp cannot be equal to MAXN - if(temp>=0&& Temp < MAXN &&!V[temp]) the { + Q.push (temp); ATime[temp] = time[cur]+1; theV[temp] =1; + } - } $ } $ } - intMain () - { theCin>>n>>K; - if(n<=k)Wuyi BFS (); the Else -cout<<n-k<<endl;//Plus, it's going to be fast. MS-POJ test Data Wu return 0; -}
ACM/ICPC algorithm Training bfs-wide search + queue Introduction-catch the Bull (POJ3278)