HDU-2717-Catch That Cow
Basic BFS, search in three directions
[Cpp]
# Include <iostream>
# Include <cstdio>
# Include <cstring>
# Include <cstdlib>
# Include <queue>
Using namespace std;
Int n, k;
Char visit [100005];
Struct node
{
Int x;
Int time;
};
Int go (int x)
{
If (0 <= x & x <= 100000)
Return 1;
Return 0;
}
Void bfs (int n, int k)
{
Queue <node> q;
Node st, ed;
Memset (visit, 0, sizeof (visit ));
Visit [n] = 1;
St. x = n;
St. time = 0;
Q. push (st );
While (! Q. empty ())
{
St = q. front ();
Q. pop ();
If (st. x = k)
{
Printf ("% d \ n", st. time );
Return;
}
If (go (2 * st. x )&&! Visit [2 * st. x])
{
Ed. x = 2 * st. x;
Ed. time = st. time + 1;
Visit [ed. x] = 1;
Q. push (ed );
}
If (go (st. x-1 )&&! Visit [st. x-1])
{
Ed. x = st. X-1;
Ed. time = st. time + 1;
Visit [ed. x] = 1;
Q. push (ed );
}
If (go (st. x + 1 )&&! Visit [st. x + 1])
{
Ed. x = st. x + 1;
Ed. time = st. time + 1;
Visit [ed. x] = 1;
Q. push (ed );
}
}
Return;
}
Int main () www.2cto.com
{
While (scanf ("% d", & n, & k )! = EOF)
{
If (n = k)
Printf ("0 \ n ");
Else
Bfs (n, k );
}
Return 0;
}
By Cambridgeacm