POJ3278 Catch That Cow(BFS)

题目点我点我点我

题目大意:输入两个数n,k两个数,问从n到k最少经过多少步,对于一个数x有三种走法,x-1,x+2,2*x。

思路:简单BFS,需要注意的是,先进行判断x-1,x+2,2*x是否有超出范围,再判断标记数组vis的值,不然会RE到你哭……不懂原因,读者若知道请务必留言告诉我,拜谢……


#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define inf 0x3f3f3f3f
const int maxn=200300;
int vis[maxn],N,K;

int bfs()
{
    vis[N]=0;
    queue<int>q;
    q.push(N);
    while(!q.empty())
    {
        int t=q.front();
        q.pop();
        if(t==K)return vis[K];
        if(2*t<maxn && vis[2*t]==-1 )
        {
            vis[2*t]=vis[t]+1;
            q.push(t*2);
        }
        if(t-1>=0 && vis[t-1]==-1 )
        {
            vis[t-1]=vis[t]+1;
            q.push(t-1);
        }
        if( t+1<maxn && vis[t+1]==-1)
        {
            vis[t+1]=vis[t]+1;
            q.push(t+1);
        }


    }
}


int main()
{
    while(~scanf("%d%d",&N,&K))
    {
        memset(vis,-1,sizeof(vis));
        printf("%d\n",bfs());
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值