Catch the Bull (POJ3278)
The farmer knows the position of a bull and wants to catch it. The farmer and the ox are all on the axis.
, the farmer starts at point N (0<=n<=100000), the Ox is located at point K (0<=k<=100000)
。 Farmers have two ways of moving:
1. Move from X to X-1 or x+1, one minute per move
2, moving from X to 2*x, each move takes a minute
Suppose the cow is not aware of the farmer's actions and stands still. The farmer must at least
How long does it take to catch a cow?
Wide Search algorithm
The breadth-first search algorithm is as follows: (with queue)
(1) Put the initial node S0 into the Open table;
(2) If the Open table is empty, the problem is not solved and the failure
Exit
(3) Remove the first node of the Open table into
Closed table, and remember that the node is n;
(4) Investigate whether node n is the target node. If
Then get the solution of the problem and exit successfully;
(5) If node n is not extensible, then move to step (2);
(6) Expand node n, not the closed table and
The sub-nodes in the open table (weighing) are placed at the end of the open table
and sets a pointer to a parent node for each child node (
or record the hierarchy of nodes) and then move to step (2).
#include <iostream> #include <queue> #include <string> #include <malloc.h>using namespace std;# Define max_size 10000//Query the maximum range int visited[max_size];//mark that location has traversed the struct node{int x;//position int step;//It takes a few steps to get to this position ( int A=0,int b=0): X (a), step (b) {}};queue<node> open;//breadth-first search, similar to a layer-by-step traversal lookup int main () {cout<< "input Farmer's position n (0 <=n<=100000): "<<endl;int n;cin>>n;cout<<" Enter the position of the Ox K (0<=k<=100000): "<<endl;int K ; Cin>>k;memset (visited,0,sizeof (visited)); Node N_start (n,0);//person position. Node K_caw (k,0);//bull position. int min_step;//The final minimum step. Node N_step (0,0);//Intermediate storage variable. N_step=n_start;open.push (n_step);//Enter the starting position into the queue Visited[n_start.x]=1;while (!open.empty ()) {N_step=open.front (); /Take out the elements of the queue header, make a Judgment open.pop (), if (n_step.x==k)//if found, then jump out of the loop {min_step=n_step.step;break;} else{//plus 1 position element if ((n_step.x+1<max_size) &&visited[n_step.x+1]==0) {Visited[n_step.x+1]=1;open.push ( Node (n_step.x+1,n_step.step+1));} if (n_step.x-1>=0&&visited[n_step.x-1]==0)//minus 1 position element {visited[n_sTep.x-1]=1;open.push (Node (n_step.x-1,n_step.step+1));} if (n_step.x*2<max_size&&visited[n_step.x*2]==0)//*2 the location of the element {Visited[n_step.x*2];open.push (Node (N_ step.x*2,n_step.step+1));}}} Cout<<min_step<<endl;system ("pause"); return 1;}
Catch the caw--(breadth-First search application, queue)