kuangbin專題一 catch the cow (BFS)

BFS例題

注意:1. 超過100000時跳出 2. 如果到右邊再回來,一定沒有直接從左邊過去划算

代碼:

// zyc 2018/8/20

#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;

typedef long long ll;
const int maxn = 100000 + 7;
const int inf = 0x3f3f3f3f;

int m, k;
int dis [maxn];
bool cheak (int l)
{
    if (l >= 0 && l <= 100000 && dis[l] == inf) return true;
    else return false;
}
void bfs ()
{
    memset (dis, inf, sizeof (dis));
    int s1, s2;
    queue <int> res;
    dis[m] = 0;
    res.push(m);
    while (!res.empty()) {
        s1 = res.front ();
        if (s1 == k) {printf ("%d\n", dis[s1]); return ;}
        res.pop();
        s2 = s1;
        if (cheak (s2 + 1)) { dis[s2 + 1] = dis[s2] + 1; res.push(s2 + 1);}
        s2 = s1;
        if (cheak (s2 * 2)) { dis[s2 * 2] = dis[s2] + 1; res.push(s2 * 2);}
        s2 = s1;
        if (cheak (s2 - 1)) { dis[s2 - 1] = dis[s2] + 1; res.push(s2 - 1);}
    }
}
int main ()
{
    while (~scanf ("%d %d", &m, &k)) {
        bfs ();
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章