POJ3278 Catch That Cow minimum number of steps the problem (BFS)

Here Insert Picture Description
Description
farmers know the location of a cow, you want to grab it. And cattle farmers are in logarithmic axis, farmer starting at point N (0 <= N <= 100000), bovine positioned at the point K (0 <= K <= 100000). The farmer has two movements: 1, to move from the X or X-1 X + 1, 2 each take a minute movement, to move from X 2 * X, take a minute movement every cow is assumed unaware farmer action, stand still. How much time it takes to seize at least cow?

Input
line: two letters separated by a space: N and K

Output
line: cattle farmers seize the minimum time required in minutes

Sample Input
5 17

Sample Output
4

Title Translation Taken: https: //blog.csdn.net/qq_40663503/article/details/98228452


BFS, or Note To update available when the team
end of each cycle to reset the arrays and queues
make the best use memset

    memset(walked, 0x3f, sizeof(walked));
    while(!queue.empty())
        queue.pop();

code show as below:

#include <cstdio>
#include <queue>
#include <cstring>

using namespace std;

int main() {

    int N,K=0;
    queue<pair<int,int> > queue;
    // 若数值*2大于15000,则肯定有更短的方式能够访问到,所以将数组大小定位150000多一点
    int walked[150005] ;
    while(scanf("%d %d",&N,&K)!=EOF)
    {
        if(K<N)
        {
            printf("%d\n",N-K);
            continue;
        }
        queue.push({N,0});
        walked[N]=1;
        while(!queue.empty())
        {
            pair<int,int> current = queue.front();
            queue.pop();
            if(current.first == K) {
                printf("%d\n",current.second);
                break;
            }
            for (int i = 0; i < 3; i++) {
                int nx;
                if (i == 0) nx = current.first - 1;
                else if (i == 1) nx = current.first + 1;
                else nx = 2 * current.first;
                // 注意判断条件
                if ((nx > 0 && nx < 2 * K && nx<150001) && walked[nx] == 0) {
                    queue.push({nx, current.second + 1});
                    walked[nx] = 1;
                }
            }
        }
        memset(walked, 0x3f, sizeof(walked));
        while(!queue.empty())
            queue.pop();
    }

    return 0;
}

Released three original articles · won praise 0 · Views 20

Guess you like

Origin blog.csdn.net/weixin_43812215/article/details/104520002
Recommended