The farmer finds the lost ox, X-> X-1, X-> x + 1, x-> 2 * X three steps, the ox does not move, seeking the shortest time to find the ox, use BFs.
# Include <iostream>
# Include <queue>
Using namespace STD;
# Define size 100005
Int tag [size];
Void BFS (int n, int K)
{
If (n = K)
{
Cout <tag [N] <Endl;
Return;
}
Int I;
Queue <int> que;
Memset (TAG, 0, sizeof (TAG ));
Que. Push (N );
Tag [N] = 0;
While (! Que. Empty ())
{
I = que. Front (); Que. Pop ();
If (I = K)
{
Cout <tag [k] <Endl;
Break;
}
If (I + 1 <= 100000 & tag [I + 1] = 0)
{
Tag [I + 1] = tag [I] + 1;
Que. Push (I + 1 );
}
If (I-1> = 0 & tag [I-1] = 0)
{
Tags [I-1] = tag [I] + 1;
Que. Push (I-1 );
}
If (2 * I <= 100000 & tag [2 * I] = 0)
{
Tag [2 * I] = tag [I] + 1;
Que. Push (2 * I );
}
Int M = que. Front ();
}
Return;
}
Int main ()
{
Int N, K;
While (scanf ("% d", & N, & K )! = EOF)
{
BFS (n, k );
}
Return 0;
}
// I just wrote another one. In fact, it's similar. I just want to train my trainer .. Both Hangzhou and Hangzhou power supply are 31 Ms
# Include <iostream>
# Include <queue>
Using namespace STD;
# Define size 100005
Bool tag [size];
Typedef struct
{
Int X;
Int step;
} Node;
Void BFS (int n, int K)
{
Int step, X, ANS = 0;
If (n = K)
{
Cout <"0" <Endl;
Return;
}
Node cur, next;
Queue <node> que;
Cur. x = N;
Cur. Step = 0;
Memset (TAG, 0, sizeof (TAG ));
Tag [N] = 1;
Que. Push (cur );
While (! Tag [k])
{
Cur = que. Front ();
Que. Pop ();
X = cur. X;
Step = cur. step;
If (x-1> = 0 & tag [x-1] = 0)
{
Tag [x-1] = 1;
Cur. x = X-1;
Cur. Step = Step + 1;
Que. Push (cur );
If (cur. x = K)
{
Ans = Step + 1;
Break;
}
}
If (x + 1 <= 100000 & tag [x + 1] = 0)
{
Tag [x + 1] = 1;
Cur. x = x + 1;
Cur. Step = Step + 1;
Que. Push (cur );
If (cur. x = K)
{
Ans = Step + 1;
Break;
}
}
If (x * 2 <= 100000 & tag [2 * x] = 0)
{
Tag [x * 2] = 1;
Cur. x = 2 * X;
Cur. Step = Step + 1;
Que. Push (cur );
If (cur. x = K)
{
Ans = Step + 1;
Break;
}
}
}
Cout <ans <Endl;
}
Int main ()
{
Int N, K;
While (scanf ("% d", & N, & K )! = EOF)
{
BFS (n, k );
}
Return 0;
}