1. 程式人生 > >Catch That Cow[POJ 3278]

Catch That Cow[POJ 3278]

Catch That Cow

//Catch That Cow : http://poj.org/problem?id=3278
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;

int n,m;
bool vis[200100];

struct node
{
    int step,time;
};

void bfs(int n)
{
    queue<node> q;
    node s;
    s.step = n;
    s.time = 0;
    q.push(s);
    while(!q.empty())
    {
        s = q.front();
        q.pop();
        int step = s.step,time = s.time;
        if(step == m)
        {
            cout<<time<<endl;
            return ;
        }
        else
        {
            if(step>0&&!vis[step-1])
            {
                vis[step-1]=1;
                s.step = step - 1;
                s.time = time + 1;
                q.push(s);
            }
            if(step<=m&&!vis[step+1])
            {
                vis[step+1] = 1;
                s.step = step + 1;
                s.time = time + 1;
                q.push(s);
            }
            if(step<=m&&!vis[2*step])
            {
                vis[2*step] = 1;
                s.step = 2 * step;
                s.time = time + 1;
                q.push(s);
            }
        }
    }
}

int main()
{
    while(cin>>n>>m)
    {
        memset(vis,0,sizeof(vis));
        bfs(n);
    }
    return 0;
}