poj 3278 Catch That Cow(记忆化广度优先搜索)

题意:

0到N的数轴上,每次可以选择移动到x-1,x+1,2*x,问从n移动到k的最少步数。

思路:

同时遍历三种可能并记忆化入队即可。

Tips:

n大于等于k时最短步数为n-k。

在移动的过程中可能会越界、重复访问。

poj不支持<bits/stdc++.h>和基于范围的for循环。

#include <iostream>
#include <queue>
using namespace std;

const int M=110000;

struct P{int x,step;};

int n,k,vis[M];

void bfs(){
    queue<P> q;
    q.push(P{n,0});
    vis[n]=1;
    while(!q.empty()){
        P now=q.front();
        q.pop();
        int x[3]={now.x-1,now.x+1,2*now.x};
        for(int i=0;i<3;i++){
            if(x[i]<0||x[i]>=M){
                continue;
            }
            else if(x[i]==k){
                cout<<now.step+1;
                return;
            }
            else if(vis[x[i]]==0){
                q.push(P{x[i],now.step+1});
                vis[x[i]]=1;
            }
        }
    }
}

int main()
{
    cin>>n>>k;
    if(n>=k){
        cout<<n-k;
    }else{
        bfs();
    }
    return 0;
}

 

posted @ 2020-03-13 18:02  Kanoon  阅读(160)  评论(0编辑  收藏  举报