POJ Problem 3278 Catch That Cow

来源:互联网 发布:linux daemon fork 编辑:程序博客网 时间:2024/05/28 15:25

John在位置N处,奶牛在K处,John每次只能有以下两种移动方式:walking和teleporting

Walking:在一个单位时间里John可以从X处移动到X-1或X+1。

Teleporting:在一个单位时间里John可以从X处移动至2*X。

假设奶牛的位置不变,求John移动到奶牛所在位置所需的最短时间。

主要方法:用队列进行宽度优先搜索BFS,同时用一个数组标记已经访问过的点,减少算法时间。注意要考虑N >= K的情况,此时,N只能一直减一,直至等于K。

#include <iostream>#include <vector>#include <queue>#include <stdio.h>using namespace std;int main(){    int n, k;    cin >> n >> k;    int ans = 0;    if(k <= n){       while(k != n){          n--;          ans++;       }       cout << ans << endl;       return 0;    }    queue<int> que;    que.push(n);    vector<int> arr(2*k+1, -1);    arr[n] = 0;    while(!que.empty()){        int s = que.size();        bool stop = false;        while(s--){            int num = que.front();            que.pop();            if(num == k) {                stop = true;                break;            }            if(num+1 <= 2*k && arr[num+1] == -1){                que.push(num+1);                arr[num+1] = ans;            }            if(num-1 >= 0 && num-1 <= 2*k && arr[num-1] == -1){                que.push(num-1);                arr[num-1] = ans;            }            if(2*num <= 2*k && arr[2*num] == -1){                que.push(2*num);                arr[2*num] = ans;            }        }        if(stop) break;        ans++;    }    printf("%d\n", ans);    return 0;}


0 0
原创粉丝点击