Idea: simple bfs search, with each location in only three directions
[Cpp]
# Include <cstdio>
# Include <cstring>
# Include <queue>
Using namespace std;
# Define N 100001
Bool s [N];
Struct node
{
Int x, time;
};
Bool limit (int x)
{
If (x> = 0 & x <= 100000)
Return true;
Else return false;
}
Void bfs (int n, int k)
{
Queue <node> q;
Node a, B;
Memset (s, false, sizeof (s ));
A. x = n; a. time = 0;
S [n] = true;
Q. push ();
While (! Q. empty ())
{
A = q. front ();
Q. pop ();
If (a. x = k)
{
Printf ("% d \ n", a. time );
Return;
}
If (limit (a. x * 2 )&&! S [a. x * 2])
{
B. x = a. x * 2; B. time = a. time + 1;
S [a. x * 2] = true;
Q. push (B );
}
If (limit (a. x-1 )&&! S [a. x-1])
{
B. x = a. X-1; B. time = a. time + 1;
S [a. x-1] = true;
Q. push (B );
}
If (limit (a. x + 1 )&&! S [a. x + 1])
{
B. x = a. x + 1; B. time = a. time + 1;
S [a. x + 1] = true;
Q. push (B );
}
}
}
Int main ()
{
Int n, k;
While (scanf ("% d", & n, & k )! = EOF)
{
If (n> = k)
Printf ("% d \ n", n-k); // when k is less than n, it can only move to the left
Else
Bfs (n, k );
}
Return 0;
}