HDU 2717 Catch That Cow --- BFS

  HDU 2717

  题目大意:在x坐标上,农夫在n,牛在k。农夫每次可以移动到n-1, n+1, n*2的点。求最少到达k的步数。

  思路:从起点开始,分别按x-1,x+1,2*x三个方向进行BFS,最先找到的一定是最小的步数。

/* HDU 2717 Catch That Cow --- BFS */
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;

bool visit[100005];
int n, k;

struct Node{
    int num;
    int step;
    Node(int lhs = 0, int rhs = 0) :num(lhs), step(rhs){}
};

inline bool judge(int x){
    if (x < 0 || x > 100000 || visit[x])
        return 0;
    return 1;
}

void bfs(){
    memset(visit, 0, sizeof visit); 
    queue<Node> q;
    visit[n] = 0; //标记起点已访问
    q.push(n);

    while (!q.empty()){
        Node x = q.front(); q.pop();
        if (x.num == k){
            printf("%d
", x.step);
            break;
        }
        Node y = x;
        ++y.step;

        //第一个方向 x-1
        y.num = x.num - 1;
        if (judge(y.num)){
            visit[y.num] = 1; //标记该点已访问
            q.push(y);
        }

        //第二个方向 x+1
        y.num = x.num + 1;
        if (judge(y.num)){
            visit[y.num] = 1; //标记该点已访问
            q.push(y);
        }

        //第三个方向 2*x
        y.num = x.num * 2;
        if (judge(y.num)){
            visit[y.num] = 1; //标记该点已访问
            q.push(y);
        }
    }//while(q)
}

int main()
{
    while (scanf("%d%d", &n, &k) == 2){
        bfs();
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/tommychok/p/5184640.html