POJ - 3278 - Catch That Cow 【bfs】

荒凉一梦 提交于 2020-02-11 06:51:10

题意

人位置在n 牛位置在k

人可以两种方式行动,而牛不动

  • 左右移动一格
  • 乘以两倍移动

思路

标准bfs,具体看代码

code

#include<iostream>
#include<queue>
#include<cstring>
#define endl '\n'
using namespace std;
const int maxn=2e5+10;
int n,k;
bool vis[maxn];
struct node{
    int x,step;
}now,nex;
int dx[]={1,-1};
int bfs(){
    memset(vis,false,sizeof(vis));
    now.x=n,now.step=0;
    queue<node>q;
    q.push(now);
    while(!q.empty()){
        now=q.front();
        q.pop();
        if(now.x==k)
            return now.step;
        for(int i=0;i<2;i++){
            nex.x=now.x+dx[i];
            nex.step=now.step+1;
            if(nex.x>=0&&nex.x<=100000)
            if(!vis[nex.x]){
                vis[nex.x]=true;
                q.push(nex);
            }
        }
        nex.x=now.x*2;
        nex.step=now.step+1;
        if(nex.x>=0&&nex.x<=100000)
        if(!vis[nex.x]){
                vis[nex.x]=true;
                q.push(nex);
        }
    }
    return 0;
}
int main(){
    while(cin>>n>>k)
        cout<<bfs()<<endl;
    return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!