题目链接:http://poj.org/problem?id=3278
代码:
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<cstring>
#include<queue>
using namespace std;
queue<int>q;
int n,k,p,a[100005];
void bfs(int n)
{
// while(!q.empty())
// {
// q.pop();
// }
// q.push(n);
while(!q.empty())
{
p=q.front();
q.pop();
if(k==p)
{
return;
}
while(p+1>=0&&p+1<=100005&&!a[p+1])
{
a[p+1]=a[p]+1;
q.push(p+1);
}
while(p-1>=0&&p-1<=100005&&!a[p-1])
{
a[p-1]=a[p]+1;
q.push(p-1);
}
while(p*2>=0&&p*2<=100005&&!a[p*2])
{
a[p*2]=a[p]+1;
q.push(p*2);
}
}
}
int main()
{
while(~scanf("%d%d",&n,&k))
{
p=0;
memset(a,0,sizeof(a));
a[n]=1;
while(!q.empty())
{
q.pop();
}
q.push(n);
bfs(n);
printf("%d\n",a[p]-1);
}
}