码迷,mamicode.com
首页 > 其他好文 > 详细

POJ3278 Catch That Cow(BFS)

时间:2018-06-12 17:43:09      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:ace   ++   输出   name   next   for   while   bfs   head   

给定两个整数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;
}

 

POJ3278 Catch That Cow(BFS)

标签:ace   ++   输出   name   next   for   while   bfs   head   

原文地址:https://www.cnblogs.com/Fy1999/p/9174153.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!