1、解题思路:经典广度搜索。

2、注意事项:设置标记数组避免重复访问。

3、实现方法:

#include<iostream>
#include
<queue>
using namespace std;

struct Node
{
int step;
int position;
};

queue
<Node> q;
int n,k,ans,flag;
int step[100010];
bool v[200010];

int main()
{
Node N,tmp;;
cin
>>n>>k;
N.position
=n;
N.step
=0;
q.push(N);
while(!q.empty())
{
N
=q.front();
if(q.front().position==k)
{
cout
<<q.front().step<<endl;
break;
}
q.pop();
tmp.position
=N.position+1;
tmp.step
=N.step+1;

if(tmp.position<=100000&&!v[tmp.position])
{
q.push(tmp);
v[tmp.position]
=true;
}
tmp.position
=N.position-1;
tmp.step
=N.step+1;
if(tmp.position>=0&&!v[tmp.position])
{
q.push(tmp);
v[tmp.position]
=true;
}
tmp.position
=N.position*2;
tmp.step
=N.step+1;
if(tmp.position<=100000&&!v[tmp.position])
{
q.push(tmp);
v[tmp.position]
=true;
}
}
return 0;
}

 

相关文章:

  • 2021-09-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-21
猜你喜欢
  • 2021-11-13
  • 2021-07-21
  • 2021-12-04
  • 2021-10-04
相关资源
相似解决方案