POJ - 3278 - Catch That Cow 【bfs】

题意

人位置在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;
}
发布了497 篇原创文章 · 获赞 1256 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/weixin_42429718/article/details/104220606