重做catch the cow

1.思路果然清晰了,十分钟搞定


#include <stdio.h>
#include <queue>
#include <iostream>
#include <cstring>

using namespace std;

int n, k;
queue <int> q;
int step[100010];

int bfs(int a)
{
    if(a == k)
        return step[k];
    else
    {
        if(a - 1 >= 0 && step[a - 1] == 0)
        {
            step[a - 1] = step[a] + 1;
            q.push(a - 1);
        }
        if(a + 1 <= 100000 && step[a + 1] == 0)
        {
            step[a + 1] = step[a] + 1;
            q.push(a + 1);
        }
        if(a * 2 <= 100000 && step[a * 2] == 0)
        {
            step[a * 2] = step[a] + 1;
            q.push(a * 2);
        }
        int temp = q.front();
        q.pop();
        bfs(temp);
    }

}

int main()
{
    while(scanf("%d%d", &n, &k) != EOF)
    {
        memset(step, 0, sizeof(step));
        bfs(n);
        cout << step[k] << endl;
    }
    return 0;
}


原文地址:https://www.cnblogs.com/dollarzhaole/p/3188963.html