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

poj3278 Catch That Cow

时间:2019-08-24 18:44:59      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:坐标   lse   ios   class   cst   位置   str   bool   ++   

题意:

在同一数轴上,有一头奶牛坐标为k,农夫的坐标为n,要从n运动到k。
有三种方法:
1. 从当前位置x运动到x+1
2. 从当前位置x运动到x-1
3. 当前位置x运动到2*x

思路:

裸裸的BFS不想多解释

直接上代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <algorithm>
#include <queue>
using namespace std;
const int N=100000;
int n,k,ans[N+5];
bool flag[N+5];
queue<int>f;

 int bfs(int n,int k)
{
    f.push(n);  ans[n]=0; flag[n]=1;
    int res,tmp;
    while (!f.empty())
    {
        res=f.front(); f.pop();
        if (res==k) return ans[res];
        for (int i=0; i<=2; i++)
        {
            if (i==0) tmp=res+1;
            else if (i==1) tmp=res-1;
            else tmp=res*2;
            if (tmp<0||tmp>N) continue;
            if (!flag[tmp])
            {
                f.push(tmp);
                flag[tmp]=1; ans[tmp]=ans[res]+1;  
            }
        }
    }
}

 int main()
{
    scanf("%d%d",&n,&k);
    if (n>=k) printf("%d\n",n-k);
    else printf("%d\n",bfs(n,k));
    return 0;
}

poj3278 Catch That Cow

标签:坐标   lse   ios   class   cst   位置   str   bool   ++   

原文地址:https://www.cnblogs.com/lyxzhz/p/11405248.html

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