原题链接:
http://acm.hdu.edu.cn/showproblem.php?pid=2717
题目大意:
从N到K最少需要几步
两种移动方式:
1. pos+1或者pos-1
2. pos*2
简单的BFS。
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<utility>
using namespace std;
const int MAXN=100000+1;
typedef pair<int,int> ii;//first位置second第几步
bool flog[MAXN];
int BFS(int N,int K)
{
memset(flog,0,sizeof(flog));
queue<ii>q;
ii pos;
pos.first=N;
pos.second=0;
q.push(pos);
flog[N]=true;
while(!q.empty())
{
pos=q.front();
q.pop();
if(pos.first==K) return pos.second;
ii temp;
if(pos.first+1<=K&&!flog[pos.first+1])//三种下一步的位置
{
temp.first=pos.first+1;
temp.second=pos.second+1;
flog[temp.first]=true;
q.push(temp);
}
if(pos.first-1>=0&&!flog[pos.first-1])
{
temp.first=pos.first-1;
temp.second=pos.second+1;
flog[temp.first]=true;
q.push(temp);
}
if(pos.first+pos.first<MAXN&&!flog[pos.first+pos.first])
{
temp.first=pos.first+pos.first;
temp.second=pos.second+1;
flog[temp.first]=true;
q.push(temp);
}
}
}
int main()
{
int N,K;
while(scanf("%d%d",&N,&K)!=EOF)
{
printf("%d\n",BFS(N,K));
}
return 0;
}