bfs poj-3278

题目:

https://vjudge.net/problem/POJ-3278

思路:

bfs

我用标记判断的时候,注意n==k的情况下

或者直接在While 循环里把if(x==k)

{return d[k];

}

#include<stdio.h>
#include<queue>
using namespace std;
const int maxn=1e5+8;
int v[maxn]={0};
int d[maxn]={0};
int n,k;
void bfs(int n)
{ d[n]=0;
   v[n]=1;
    queue<int> q;
    q.push(n);
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        int t;
        t=x-1;
        if(t>=0&&t<=100000&&!v[t])
        {
            v[t]=1;
            d[t]=d[x]+1;
            q.push(t);
        }
        t=x+1;
           if(t>=0&&t<=100000&&!v[t])
        {
            v[t]=1;
            d[t]=d[x]+1;
            q.push(t);
        }
        t=2*x;
         if(t>=0&&t<=100000&&!v[t])
        {
            v[t]=1;
            d[t]=d[x]+1;
            q.push(t);
        }
    }
    if(d[k])
    {
        printf("%d\n",d[k]);
        return;
    }
}
int main()
{
    scanf("%d %d",&n,&k);
    if(n==k)
        printf("0\n");
    else if(n>k)
        printf("%d\n",n-k);
    else
    bfs(n);
}

 

posted @ 2021-07-05 20:43  废柴废柴少女  阅读(21)  评论(0)    收藏  举报