POJ-3278 catch that cow 广度优先搜索

以牛的位置为起始点向前搜索,注意状态更新就好了


不要问我为什么是从后往前搜...我也不知道,我第一遍从前往后搜的wa了 然后换从后往前搜就AC了...


#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;

int dis[100005];
int bfs(int n){
    for(int i=0;i<=100000;i++){
        dis[i]=99999999;
    }
    queue<int>q;
    q.push(n);
    dis[n]=0;
    while(!q.empty()){
        int t=q.front();
        q.pop();
        if(dis[t-1]>dis[t]+1&&t>=1){
            dis[t-1]=dis[t]+1;
            q.push(t-1);
        }
        if(dis[t+1]>dis[t]+1&&t<=100000){
            dis[t+1]=dis[t]+1;
            q.push(t+1);
        }
        if(t%2==0)
        if(dis[t/2]>dis[t]+1&&t>=0){
            dis[t/2]=dis[t]+1;
            q.push(t/2);
        }
    }
}

int main()
{
    int N,K;
    while(cin>>N>>K){
            bfs(K);
            cout<<dis[N]<<endl;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值