POJ - 3278 Catch That Cow (bfs)

Meaning of the questions: Farmer in n, cows m, the farmer can conduct some operations:

FJ can move from any point X to the points - 1 or + 1 in a single minute
FJ can move from any point X to the point 2 × X in a single minute.

That farmer may be x-1, x + 1,2 * x three operations, Q may be caught within a minimum of several cows.

First, if n> m, the farmer can only be sure to return the x-1 operations, in order to catch the cow, which is required to spend nm operations.

This is a channel of water BFS template question, starting from the position of the farmer, for the duration of n-1, n + 1,2 * n to search, the search returns to the step count.

code show as below:

#include <iostream>
#include <stdio.h>
#include <math.h>
#include <queue>
#include <string.h>
int flag[100002];
using namespace std;
int n,m,cnt;
queue<int> q;
int bfs(int i,int j)
{
    q.push(i);
    int date,d;
    flag[i]=1;
    while(!q.empty())
    {
        date=q.front();
        q.pop();
        for(int k=0;k<3;k++)
        {
            if(k==0)
                d=date+1;
            else if(k==1)
                d=date-1;
            else if(k==2)
                d=date*2;
            if(d>=0&&d<=100000&&flag[d]==0)
            {
                flag[d]=flag[date]+1;
                //printf("%d   %d\n",d,flag[d]);
                q.push(d);
                if(d==j)
                    return flag[d]-1;
            }
        }
    }
    return 0;
}
int main ()
{
    while(cin>>n>>m)
    {
        memset(flag, 0, sizeof(flag));
        cnt=0;
        if(n>m)
            printf("%d\n",n-m);
        else
            printf("%d\n",bfs(n, m));
    }
}

Guess you like

Origin blog.csdn.net/hrbust_cxl/article/details/88577241