给你两个点N,K,从N到K,你有三种移动方案:①N-1②N+1③N*2让你用这三种方案达到K点,问最少需要多少步?
#include<iostream>
#include<algorithm>
#include<queue>
#include<string.h>
#include<cstdio>
#define max 100001
using namespace std;
struct node
{
int n;
int step;
bool friend operator < ( node a , node b )
{
return a.step>b.step;
}
};
int N,K;
int vis[100010];
void bfs(int N)
{
int ans;
priority_queue<node>q;
node p,tem;
p.step=0;
p.n=N;
q.push(p);
while(!q.empty())
{
tem=q.top();
q.pop();
if(tem.n==K)
{
printf("%d\n",tem.step);
// printf("ans=%d\n",tem.n);
return ;
}
if(tem.n-1>=0&&tem.n-1<max&&!vis[tem.n-1])
{
vis[tem.n-1]=1;
p.n=tem.n-1;
p.step=tem.step+1;
q.push(p);
}
if(tem.n+1>=0&&tem.n+1<max&&!vis[tem.n+1])
{
vis[tem.n+1]=1;
p.n=tem.n+1;
p.step=tem.step+1;
q.push(p);
}
if(tem.n*2>=0&&tem.n*2<max&&!vis[tem.n*2])
{
vis[tem.n*2]=1;
p.n=tem.n*2;
p.step=tem.step+1;
q.push(p);
}
}
}
int main()
{
while(scanf("%d%d",&N,&K)!=EOF)
{
memset(vis,0,sizeof(vis));
bfs(N);
// printf("%d\n",bfs(N));
}
return 0;
}