poj bfs3278

#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
int n,k;
int x;
int d[100010],ff[100010];
int bfs()
{
    
    
    queue<int>q;
    q.push(n);
    d[n]=0;
    ff[n]=1;
    while(!q.empty())
    {
    
    
        int x=q.front();
        q.pop();
        for(int i=0; i<4; i++)
        {
    
    
            int xx;
            if(i==0)
                xx=x+1;
            if(i==1)
                xx=x-1;
            if(i==2)
                xx=2*x;
            if(xx>=0&&xx<=100000&&!ff[xx])
            {
    
    
                ff[xx]=1;
                d[xx]=d[x]+1;
                q.push(xx);
            }
            if(xx==k)return d[xx];
        }

    }
    return -1;

}
int main()
{
    
    
    scanf("%d%d",&n,&k);
    memset(d,-1,sizeof d);
    memset(ff,0,sizeof ff);
    cout<<bfs();
}

题目不难,细心即可。

猜你喜欢

转载自blog.csdn.net/weixin_51626694/article/details/116135553