Virtual Judge POJ 3278 Catch That Cow

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<queue>
const int  maxn =100010;
using namespace std;
int n,m;
struct data {
    int x,step;
} p;
int vis[100005];
void bfs() {
    memset(vis,0,sizeof(vis));  //重置
    queue<data>q;  //队列
    p.x=n;  //起点
    p.step=0;  //起点到起点的距离
    q.push(p);  //压入队列
    vis[n]=1;  //走过
    while(!q.empty()) {
        p=q.front();
        q.pop();
        if(p.x==m) {
            printf("%d\n",p.step);  //直接输出
            return ;
        }
        data k=p;
        if(k.x+1<maxn&&!vis[k.x+1]) {  //尝试前进一步
            k.x++;  //如果可以,加坐标
            vis[k.x]=1;  //标记走过
            k.step++;  //  加步数
            q.push(k); //新的位置压入队列

        }
        k=p;
        if(k.x-1>=0&&!vis[k.x-1]) { //尝试后退一步
            k.x--;
            vis[k.x]=1;
            k.step++;
            q.push(k);
        }
        k=p;
        if(k.x*2<maxn&&!vis[k.x*2]) { //尝试传送
            k.x*=2;
            vis[k.x]=1;
            k.step++;
            q.push(k);
        }
    }
}
int main() {
    scanf("%d%d",&n,&m);
    bfs();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/QingyuYYYYY/p/11746394.html
今日推荐