例题9.1 Catch That Cow

//个人感觉BFS挺简单的,就调用一个函数就行
#include <iostream>
#include <queue>
#include <cstring>//memset
using namespace std;

struct Pos
{
   int pos;
   int t;
   Pos(int pos,int t):pos(pos),t(t){}
};

bool visit[100000];
void BFS(int n,int k)
{
    queue<Pos> q;
    Pos current(n,0);
    q.push(current);
    visit[n]=true;
    
    while(!q.empty())
    {
        Pos cur=q.front();
        q.pop();
        if(cur.pos==k){
             cout<<cur.t<<endl;
             break;
        }
        
        
        for(int i=1;i<=3;i++)
        {
            Pos nextpos(0,0);//必须要初始化
            if(i==1){
                nextpos.pos=cur.pos-1;
                nextpos.t=cur.t+1;
            }
            else if(i==2){
                nextpos.pos=cur.pos+1;
                nextpos.t=cur.t+1;
            }
            else
            {
                nextpos.pos=cur.pos*2;
                nextpos.t=cur.t+1;
            }
            if(nextpos.pos<0||nextpos.pos>100000||visit[nextpos.pos]==true)
            {
                continue;
            }
            q.push(nextpos);
            visit[nextpos.pos]=true;
        }
    }
        
}

int main()
{
    int m;cin>>m;
    int n,k;
    for(int i=1;i<=m;i++)
    {
        cin>>n>>k;
        memset(visit,false,sizeof(visit));
        BFS(n,k);
    } 
}
全部评论

相关推荐

今天刚通知oc
跑不快的yyyf:接好运
点赞 评论 收藏
分享
08-08 16:33
唐山学院 Java
职场水母:首先,简历太长,对于实习和应届找工作,hr一眼扫的是学历,技术看实习,你写的技术栈字太多了,尽量用一句话概括不用写那么详细,技术面的时候会问的,而且技术栈都会在实习或者项目里体现,你要做的是,把你的简历浓缩为一页,删除没用的东西,比如实践经历,自我评价,这些纯废话,没用,专业技能写的太离谱,你真的熟练掌握了吗,建议都写熟悉,找工作和写论文不一样,追求的是干练和实用,把实习经历和项目提前,把掌握的技术栈写到最后,然后去找实习,
点赞 评论 收藏
分享
09-01 21:40
已编辑
同济大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务