POJ - 3278 Catch That Cow

POJ - 3278链接
这又是一道bfs板子题,主要操作有坐标减一,坐标加一,坐标乘二,只要记录这些步骤的状态就好了,直接上代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 1e5 + 10;
int visit[N], n, k;
void bfs() {
    queue<PII> q;
    q.push(make_pair(n, 0));
    visit[n] = 1;
    while(!q.empty()) {
        PII temp = q.front();
        q.pop();
        if(temp.first == k) {
            printf("%d\n", temp.second);
            break;
        }
        if(temp.first - 1 >= 0 && !visit[temp.first - 1]) {//坐标减一
            visit[temp.first - 1] = 1;
            q.push(make_pair(temp.first - 1, temp.second + 1));
        }
        if(temp.first  + 1 <= N && !visit[temp.first + 1]) {//坐标加一
            visit[temp.first + 1] = 1;
            q.push(make_pair(temp.first + 1, temp.second + 1));
        }
        if(temp.first * 2 <= N && !visit[temp.first * 2]) {//坐标乘二
            visit[temp.first * 2] = 1;
            q.push(make_pair(temp.first * 2, temp.second + 1));
        }
    }
}
int main() {
    while(cin >> n >> k) {
        memset(visit, 0, sizeof visit);
        bfs();
    }
}
posted @ 2020-01-19 11:05  lifehappy  阅读(81)  评论(0编辑  收藏  举报