pku 3278 Catch That Cow BFS

http://poj.org/problem?id=3278

就是农场主在X轴上找牛,给定牛的坐标,扭不动,农场主可以 +1 -1 *2 的方式前进,求最少的步数使其找到牛。

分三种情况走,直到遇到牛即可,同时为了避免不断的重复于某一点,记录到达该点的最短距离。

View Code
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#define maxn 100007
#define inf 9999999
using namespace std;

int ans,s,e;
struct node
{
    int len;
    int pos;
}p[maxn];//用来记录到达该点的最短距离

//判断是否出界
bool isok(int x)
{
    if (x >= 0 && x <= 100000) return true;
    else return false;
}
int bfs()
{
    int i;
    int sum = 0;
    node ss;
    ss.len = 0;
    ss.pos = s;
    p[s].len = 1;
    queue<node>q;
    q.push(ss);
    while (!q.empty())
    {
        node cur = q.front(); q.pop();
        if (cur.pos == e)
        {
            sum = cur.len;
            break;
        }
        node t;
        for (i = 0; i < 3; ++i)
        {
            if (i == 0 && isok(cur.pos + 1))
            {
                t.pos = cur.pos + 1;
                if (p[t.pos].len > cur.len + 1)
                {
                    t.len = cur.len + 1;
                    p[t.pos].len = cur.len + 1;
                    q.push(t);
                }
            }
            if (i == 1 &&  isok(cur.pos - 1))
            {
                t.pos = cur.pos - 1;
                if (p[t.pos].len > cur.len + 1)
                {
                    t.len = cur.len + 1;
                    p[t.pos].len = cur.len + 1;
                    q.push(t);
                }
            }
            if (i == 1 &&  isok(cur.pos*2))
            {
                t.pos = cur.pos*2;
                if (p[t.pos].len > cur.len + 1)
                {
                    t.len = cur.len + 1;
                    p[t.pos].len = cur.len + 1;
                    q.push(t);
                }
            }
        }
    }
    return sum;
}
int main()
{
    for (int i = 0; i <= 100000; ++i) p[i].len = inf;
    scanf("%d%d",&s,&e);
    int ans = bfs();
    printf("%d\n",ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值