POJ 3278 Catch That Cow

BFS基础框架题,写在这里只是为了让大家对于BFS有个更好的理解

对于我也是,我一开始也不知道BFS和DFS能做些什么,只知道可以用来走迷宫,发现还是蛮有趣的,现在更加有趣了。

这道题目很容易理解,给你两个数,三种操作,问N是否能通过这三种操作将N变成K.

看着数据量暴力肯定超时,所以当时直接就想到了BFS,

的确BFS是蛮快的,但是费内存(果然,一开始没有写一个数组用于标记是否某个数已经被到达过...果然队列爆了= =)

下面是代码,还是蛮好理解的

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <queue>
#include <stack>
using namespace std;
const int maxn=100001;
bool vis[maxn];
struct node
{
    int x;
    int step;
}now,next;
int n,k;
int bfs()
{
    queue<node> q;
    now.x=n;
    now.step=0;
    q.push(now);
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        for(int i=0;i<3;i++)
        {
            if(i==0)
            {
                next.x=now.x+1;
                next.step=now.step+1;
            }
            else if(i==1)
            {
                next.x=now.x-1;
                next.step=now.step+1;
            }
            else
            {
               next.x=now.x*2;
               next.step=now.step+1;
            }
            if(next.x>maxn||next.x<0)
                continue;
            if(!vis[next.x])
            {
                q.push(next);
                vis[next.x]=1;
            }
            if(next.x==k)
                return next.step;
        }
    }
    return -1;
}
int main()
{
    while(scanf("%d%d",&n,&k)!=EOF)
    {
        memset(vis,0,sizeof vis);
        if(n>=k)
            printf("%d\n",n-k);
        else
            printf("%d\n",bfs());
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值