题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2717
方法:bfs
思路:由于搜索空间还是很大的,如果用bfs的话很容易就会造成递归堆栈溢出,而且时间复杂度也会很高,所以采用bfs。这是我第一次手写bfs,借鉴了一下网上高手的经验,在此谢过。原理都是不难,只需要按照bfs的步骤一步步来就可以了。由于这里需要记录两个数据,因此会用到结构体,这样的话直接用STL里的queue会省很多事儿。
难点:queue的使用
参考链接:
本题 :http://blog.csdn.net/libin56842/article/details/9017449
queue: http://blog.csdn.net/morewindows/article/details/6950917
#include<iostream>
#include<climits>
#include<queue>
#include<cstring>
using namespace std;
int n,k;
const int N = 1000000;
int mark[N] = {0};
struct node
{
int x;
int time;
};
int check(int x)
{
if(x > N || x < 0 || mark[x] == 1)
return 0;
else
return 1;
}
int bfs(int x)
{
node p,nextp;
queue<node> Q;
p.x = x;
p.time = 0;
mark[x] = 1;
Q.push(p);
while(!Q.empty())
{
p = Q.front();
Q.pop();
if(p.x == k)
{
return p.time;
}
nextp.x = p.x+1;
if(check(nextp.x))
{
nextp.time = p.time+1;
Q.push(nextp);
mark[nextp.x] = 1;
}
nextp.x = p.x-1;
if(check(nextp.x))
{
nextp.time = p.time+1;
Q.push(nextp);
mark[nextp.x] = 1;
}
nextp.x = p.x*2;
if(check(nextp.x))
{
nextp.time = p.time+1;
Q.push(nextp);
mark[nextp.x] = 1;
}
}
return -1;
}
int main()
{
while(cin>>n>>k)
{
memset(mark,0,sizeof(mark));
int ans = bfs(n);
cout<<ans<<endl;
}
}