Title Link: http://poj.org/problem?id=3278
Test instructions
On a number (0 ~ 100000), give you farmer J's position n, and the position of the Bull Cow K, the farmer has three ways of moving: Move left one step (X-1,x is the current position), move right one step (x + 1), move right 2*x step (2 * x), ask the farmer to move at least how many steps can catch up Cows are not moving in situ.
Ideas:
Since the question is how many steps to move at least, the most easily thought of is violence, assuming that starting from the beginning of each step has three choices, choose a point, then there are three options .... In this way, a complete three-fork tree is constructed, that is, the solution space of the problem. Because the problem is the shortest distance, that is, as shallow as possible access to the target point in the tree. It is very obvious that BFS is used.
Attention:
The lower bound of the point is 0 and the upper bound is 100000, so the BFS should determine whether the point is within the bounds before it is accessed. Simply ate four or five rounds of re ...
Code:
1#include <iostream>2#include <cmath>3#include <cstdio>4#include <cstring>5#include <cstdlib>6#include <stack>7#include <queue>8#include <vector>9#include <algorithm>Ten#include <string> One AtypedefLong LongLL; - using namespacestd; - Const intMAXN =100000; the intVISIT[MAXN +3];//Tag Array - intFJ, cow; - -typedefstructPoint {intXintStep;} Poi; + - intCheckintK) {//determine if the point is within bounds + if(k >=0&& k <= MAXN)return 1; A return 0; at } - - intBFS (Poi St) {//Search the solution tree starting from the farmer's starting point -Queue<poi>Qu; - Qu.push (ST); -Visit[st.x] =1; in intAns =-1; - while(!Qu.empty ()) { to Poi now; +now =Qu.front (); - Qu.pop (); theAns =Now.step; * if(now.x = = Cow) Break;//reach Target Point $ if(Check (now.x +1) &&!visit[now.x +1]) {//determine the range of points before judging whether to access, three if the three mobile modePanax Notoginseng Poi NEX; -nex.x = now.x +1, Nex.step = Now.step +1; the Qu.push (NEX); +VISIT[NEX.X] =1; A } the if(Check (now.x-1) &&!visit[now.x-1]) { + Poi NEX; -nex.x = now.x-1, Nex.step = Now.step +1; $ Qu.push (NEX); $VISIT[NEX.X] =1; - } - if(Check (now.x *2) &&!visit[now.x *2]) { the Poi NEX; -nex.x = now.x *2, Nex.step = Now.step +1;Wuyi Qu.push (NEX); theVISIT[NEX.X] =1; - } Wu } - returnans; About } $ - intMain () { - while(~SCANF ("%d%d", &FJ, &Cow)) { -memset (Visit,0,sizeof(visit)); A Poi St; +St.x = FJ, St.step =0; theprintf"%d\n", BFS (ST)); - } $ return 0; the}
POJ3278 Catch that Cow (BFS)