POJ 3278 Catch That Cow

Catch That Cow http://poj.org/problem?id=3278

BFS 注:&& 前后顺序有影响,记得先判断范围,不然就越界了!!

代码

#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>

using namespace std;
queue<int> q;
const int N = 1e5 + 5;
int dis[N];
int n, k;

bool Range (int x) {
    if (x >= 0 && x <= (int)1e5)
        return true;
    return false;
}

void change (int v, int u) {
    
    if (Range(v) && dis[v] == 0x3f3f3f3f  ){
        dis[v] = dis[u] + 1;
        q.push(v); //别忘了更新
    }
}

void bfs (int x) {
    memset (dis, 0x3f, sizeof dis);
    q.push (x);
    dis[x] = 0;

    while (!q.empty()) {
        int u = q.front();

        if (u == k) {
            cout << dis[u] << endl;
            return;
        }
        //cout << u  << ' ' << dis[u] << endl;
        q.pop();

        
        change (u + 1, u);
        change (u * 2, u);
        change (u - 1, u);
    } 
    

}

int main () {
    
    cin >> n >> k;
    bfs (n);
   //cout << dis[k] << endl;
}
posted @ 2022-04-03 22:59  Sakana~  阅读(16)  评论(0编辑  收藏  举报