POJ 3278 Catch That Cow

【分析】简单bfs,来不及解释了,快上车。

【AC代码】

#include<iostream>
#include<queue>
#include<string.h>
#include<stdio.h>
using namespace std;
const int maxn=100001;
bool vis[maxn];
int step[maxn];
queue <int> q;
int bfs(int n,int k)
{
    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()
{
        int n,k;
        scanf("%d %d",&n,&k);
        memset(step,0,sizeof(step));
        memset(vis,false,sizeof(vis));
        while(!q.empty()) q.pop();
        if(n>=k) printf("%d\n",n-k);
        else printf("%d\n",bfs(n,k));
        return 0;
}


你可能感兴趣的:(POJ 3278 Catch That Cow)