HDU 2717 Catch That Cow (BFS)


**链接 : ** Here!

**思路 : ** 很简单, 就是一个简单的状态搜索, 对于中间的任意状态 $number$ , 它都有三种转移方式 : 1.$(number - 1)$, 2.$(number + 1)$, 3.$(number * 2)$, 所以直接 $BFS$ 就好了, 需要注意的是判断一下最大值是否已经超出 $MAX_N$ 了, 否则容易数组越界......, 而且在 $Vjudge$ 上好像不支持 "{}" 构造......


/*************************************************************************
	> File Name: E.cpp
	> Author: 
	> Mail: 
	> Created Time: 2017年11月26日 星期日 10时51分05秒
 ************************************************************************/

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
using namespace std;

#define MAX_N 2000010
int N, K;
int vis[MAX_N];
struct Point {
    Point(int ind, int step) : ind(ind), step(step){}
    int ind, step;
};

bool check(Point pt) {
    if (pt.ind < 0 || pt.ind >= MAX_N)  return false;
    if (vis[pt.ind]) return false;
    return true;
}

int BFS() {
    vis[N] = 1;
    queue<Point> que;
    que.push(Point{N, 0});
    while (!que.empty()) {
        Point now = que.front();
        que.pop();
        if (now.ind == K) {
            return now.step;
        }
        // 看起来并不支持{}构造
        // case 1:
        
            Point temp1(Point(now.ind - 1, now.step + 1));
            if (check(temp1)) {
                que.push(temp1);
                vis[temp1.ind] = 1;
            }
        
        // case 2:
        
            Point temp2(Point(now.ind + 1, now.step + 1));
            if (check(temp2)) {
                que.push(temp2);
                vis[temp2.ind] = 1;
            }
        
        // case 3:
        
            Point temp3(Point(now.ind * 2, now.step + 1));
            if (check(temp3)) {
                que.push(temp3);
                vis[temp3.ind] = 1;
            }
        
    }
    return -1;
}
void solve() {
    memset(vis, 0, sizeof(vis));
    int ret = BFS();
    printf("%d\n", ret);
}
int main() {
    while (scanf("%d%d", &N, &K) != EOF) {
        solve();
    }
    return 0;
}
posted @ 2017-11-27 10:02  ojnQ  阅读(121)  评论(0编辑  收藏  举报