题目:
hdoj : http://acm.hdu.edu.cn/showproblem.php?pid=2717
思路:
利用BFS的逐步搜索来实现最短少用时,和数组记录来排除不需要的点。
AC代码:
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int M = 200100;
int d[M];
int a, b;
int bfs()
{
queue<int> q;
q.push(a);
memset(d, -1, sizeof(d));
d[a] = 0;
while(!q.empty())
{
int tmp = q.front();
q.pop();
int n1 = tmp * 2, n2 = tmp - 1, n3 = tmp + 1;
if(n1 == b || n2 == b || n3 == b)
{
while(!q.empty())
q.pop();
return d[tmp] + 1;
}
if(n1 < M && d[n1] == -1)//如果这个点不是-1,说明这个点之前经历过,无需再走。
{
d[n1] = d[tmp] + 1;
q.push(n1);
}
if(n2 >= 0 && d[n2] == -1)
{
d[n2] = d[tmp] + 1;
q.push(n2);
}
if(n3 < M && d[n3] == -1)
{
d[n3] = d[tmp] + 1;
q.push(n3);
}
}
}
main()
{
while(cin >> a >> b)
{
if(a >= b)
{
printf("%d\n", a - b);
continue;
}
printf("%d\n", bfs());
}
}