题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2717
题目大意是:在一条坐标轴上,从一个点到另一个点的最小移动步数,移动方法有两种,一是向左走一步或是向右走一步,二是瞬移到当前坐标的二倍处。
解题思路:因为题目询问的是最短步数,且有三种走的方法,所以很直接就想到用BFS来实现。
具体代码如下:
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
const int lim=100005;
int dirx[2]={1,-1};
int flag[lim];
int N,K;
struct point
{
int x;
int step;
};
void bfs();
bool judge(point p)
{
if(p.x<0 || p.x>100000 || p.step>flag[p.x])//注意一定要进行边界判断
{
return false;
}
return true;
}
int main ()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
while(~scanf("%d%d",&N,&K))
{
if(N==K)
{
cout<<0<<endl;
continue ;
}
memset(flag,0X7F, sizeof(flag)); //
bfs();
}
return 0;
}
void bfs()
{
int i;
point node, t;
flag[N]=0;
node.x=N;
node.step=0;
queue<point> q;
while(!q.empty())//重要!
{
q.pop();
}
q.push(node);
while(!q.empty())
{
node=q.front();
q.pop();
for(i=0; i<3; i++)
{
t=node;
if(i==2)
{
t.x*=2;
}
else
{
t.x+=dirx[i];
}
t.step=node.step+1;
if(!judge(t))continue;
if(t.x==K)
{
cout<<t.step<<endl;
return ;
//第一个到达的即为最小值;
}
flag[t.x]=t.step;
q.push(t);
}
}
}
仅代表个人观点,欢迎交流探讨,勿喷~~~
PhotoBy:WLOP