原题链接:
http://acm.hdu.edu.cn/showproblem.php?pid=2717
题目大意:
输入一个N和K。表示你的起点是N。终点为K。每次有3中移动方式。
1.移动到X+1 的位置
2.移动到X-1的位置
3.移动到2X的位置
X为你当前的位置。问从N开始。最少走几步才能到K
思路:
这时一道简单的BFS水题。按一般做法来解决就可以了
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
int vis[100005];
int Pre[100005];
int N,K,number;
using namespace std;
void GetCount( int Index )
{
while( Pre[ Index ] != -1 )
{
Index = Pre[ Index ];
number++;
}
}
bool IsLeagal( int Next )
{
if( Next < 0 || Next >= 100005 )
return false;
return true;
}
void bfs()
{
queue<int> line;
memset( Pre,0,sizeof(Pre));
memset( vis,0,sizeof(Pre));
vis[ N ] = true;
Pre[ N ] = -1;
line.push ( N );
int Now,next_1,next_2,next_3;
while( !line.empty ())
{
Now = line.front ();
line.pop ();
if( Now == K )
{
return ;
}
next_1 = Now +1;
if( !vis[next_1] && IsLeagal(next_1) )
{
Pre[next_1] = Now;
vis[next_1] = true;
line.push ( next_1 );
}
next_2 = Now - 1;
if( !vis[next_2] && IsLeagal(next_2) )
{
Pre[next_2] = Now;
vis[next_2] = true;
line.push ( next_2 );
}
next_3 = Now * 2;
if( !vis[next_3] && IsLeagal(next_3))
{
Pre[next_3] = Now;
vis[next_3] = true;
line.push ( next_3 );
}
}
}
int main()
{
while( cin >> N >> K)
{
number = 0;
bfs();
GetCount( K );
cout<<number<<endl;
}
return 0;
}