POJ3278 Catch That Cow(BFS)

给定两个整数n和k,通过 n+1或n-1 或n*2 这3种操作,使得n==k

输出最少的操作次数

#include<iostream>
#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;

const int maxn=100001;

bool visit[maxn];
int step[maxn];
queue <int> q;

int bfs(int n,int k)
{
    int head,next;
    q.push(n);
    step[n]=0;
    visit[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(!visit[next])
            {
                q.push(next);
                step[next]=step[head]+1;
                visit[next]=true;
            }
            if(next==k) return step[next];
        }

    }
}
int main()
{
    int n,k;
    cin>>n>>k;
    cout<<bfs(n,k)<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Fy1999/p/9174153.html