(简单)队列加搜索

这道题,一看就知道是搜索题。但它有三条选择的方式移动,那么我们就可以运用队列的知识进行暴力的搜索(因为必定对找到出口)。
#include<cstdio>
#include<queue>
#include<cstring>
#include<cmath>
using namespace std;
int a[200010];
struct P                        //定义一个结构体存当前的点和到这个点的最少步数
{
    int n,x;
};
int main()
{
    int n,k;
    while(~scanf("%d%d",&n,&k))
    {
        if(n==k)
            printf("0\n");
            else
        if(n>k)
            printf("%d\n",n-k);
            else

        {
             memset(a,0,sizeof(a));
            queue <P> q;
            P p;
            p.n=n;
            p.x=0;
            q.push(p);
            a[n]=1;
            while(1)                   //因为必定会找到出口,所以用while(1)
            {
                int t=q.front().n;          //每次用队首元素进行搜素

                if(t+1==k||t-1==k||2*t==k){
                    printf("%d\n",q.front().x+1);
                    break;
                }

                if( t>0 &&a[t-1]==0 )
                {
                    a[t-1]=1;
                    p.n=t-1;
                    p.x=q.front().x+1;
                    q.push(p);

                }

                if( t<100001 && a[t+1]==0 )
                {
                    a[t+1]=1;
                    p.n=t+1;
                    p.x=q.front().x+1;
                    q.push(p);

                }

                if(2*t<100001 && a[t*2]==0 )
                {
                     a[t*2]=1;
                    p.n=t*2;
                    p.x=q.front().x+1;
                    q.push(p);

                }
                q.pop();
            }
        }
    }
    return 0;
}

相关文章:

  • 2021-06-14
  • 2021-09-29
  • 2022-12-23
  • 2021-11-18
  • 2021-06-01
  • 2021-07-05
  • 2022-01-07
  • 2021-08-06
猜你喜欢
  • 2022-12-23
  • 2022-01-31
  • 2021-09-01
  • 2021-09-10
  • 2022-12-23
  • 2022-03-10
  • 2021-08-21
相关资源
相似解决方案