NOI:2971 抓住那头牛


题目链接:http://noi.openjudge.cn/ch0205/2971/

题解:这道题可以使用典型的BFS求解,一提到求最短路问题,就会想到BFS(需要有这个意识)

#include <stdio.h>
#include <iostream>
#include <queue>
using namespace std;
int size;
int n,k;
struct point {
    int x,tmp;
    point(int x1,int tmp1){
        x=x1;
        tmp=tmp1;
    }
    point(){
        x=0;
        tmp=0;
    }
};
queue<point> a;
bool b[100005];//判断当前点是否遍历过
void test(){//典型的bfs
    point t(n,0);
    a.push(t);
    while(!a.empty()){
        t=a.front();
        a.pop();
        if(t.x==k){
            size=t.tmp;
            return;
        }else{
            if((t.x+1)<=100000&&b[t.x+1]){
                point t2(t.x+1,t.tmp+1);
                b[t.x+1]=false;
                a.push(t2);
            }
            if(t.x-1>=0&&b[t.x-1]){
                point t2(t.x-1,t.tmp+1);
                b[t.x-1]=false;
                a.push(t2);
            }
            if((t.x*2)<=100000&&b[t.x*2]){
                point t2(t.x*2,t.tmp+1);
                b[t.x*2]=false;
                a.push(t2);
            }
        }
    }
}
int main(){
    cin>>n>>k;
    for(int i=0;i<100005;i++){
        b[i]=true;
    }
    size=0;
    test();
    cout<<size<<endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值