C - Catch That Cow (vj)

bfs+队列,算是一道很经典的题,不过当自己去写的时候还是有点懵(下面的代码来自这篇博客


#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
int n,k;
int step[maxn];
bool vis[maxn];
queue<int>Q;
int bfs()
{
    int head,next;
    Q.push(n);
    step[n]=0;
    vis[n]=true;
    while(!Q.empty())
    {
        head=Q.front();
        Q.pop();
        for(int i=0;i<3;i++)
        {
            if(i==0) next=head-1;
            else if(i==1) next=head+1;
            else next=head*2;
            if(next<0||next>=maxn) continue;
            if(!vis[next])
            {
                Q.push(next);
                step[next]=step[head]+1;
                vis[next]=true;
            }
            if(next==k) return step[next];
        }
    }

}
int main()
{
    while(scanf("%d%d",&n,&k)==2)
    {
        if(n>=k) printf("%d\n",n-k);
        else
        {
            while(!Q.empty()) Q.pop();
            memset(vis,false,sizeof(vis));
            memset(step,0,sizeof(step));
            printf("%d\n",bfs());
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41061455/article/details/80347596