C - Catch That Cow (POJ - 3278)
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int N = 1e5+5;
bool vis[N] = {0};
int n, k, ans = 0;
struct P {
int x;
int step;
};
int bfs() {
memset(vis, 0, sizeof(vis));
P sp;
sp.x = n;
sp.step = 0;
queue<P> q;
q.push(sp);
vis[sp.x] = 1;
while(!q.empty()) {
P tp = q.front();
q.pop();
if(tp.x==k) {
return tp.step;
}
P np = tp;
np.x = tp.x - 1;
if(np.x>=0 && !vis[np.x]) {
np.step = tp.step+1;
q.push(np);
vis[np.x] = 1;
}
np.x = tp.x + 1;
if(np.x<=N && !vis[np.x]) {
np.step = tp.step+1;
q.push(np);
vis[np.x] = 1;
}
np.x = tp.x * 2;
if(np.x<=N && !vis[np.x]) {
np.step = tp.step+1;
q.push(np);
vis[np.x] = 1;
}
}
return 0;
}
int main(void) {
scanf("%d%d", &n, &k);
if(n>k)
ans = n-k;
else
ans = bfs();
printf("%d\n", ans);
return 0;
}