Catch That Cow

原题链接

题意解释

一个人从数轴上的某一点x出发,要去数轴上的另一个点y,只有每分钟可以选择步行x + 1x - 1和传送x * 2这三种走法,问最少需要多少时间才能走到y点

题解

使用一个BFS直接跑就可以了,用一个数组标记一下这个点是否到达过,如果到达过,这个点就不能再走了,因为BFS第一次搜到的就是最短的时间,这样做也节约了程序跑的时间

代码如下

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

using namespace std;
const int N = 100010;
typedef struct Node{
    int a, b;
}node;
bool st[N];//标记一下,第一次走过的点一定是耗时最少的,下一次就不能再走了,也节约了时间

int main(){
    int n, m;
    cin >> n >> m;
    node tm;
    queue<node> q;
    tm.a = n, tm.b = 0;
    q.push(tm);
    while(q.size()){
        node t = q.front(); q.pop();
        if(t.a == m) {cout << t.b << '\n'; break;}
        if(t.a + 1 < N && !st[t.a + 1])
        tm.a = t.a + 1, tm.b = t.b + 1, q.push(tm), st[t.a + 1] = true;
        if(!st[t.a - 1])
        tm.a = t.a - 1, tm.b = t.b + 1, q.push(tm), st[t.a - 1] = true;
        if(t.a * 2 < N && !st[t.a * 2])
        tm.a = t.a * 2, tm.b = t.b + 1, q.push(tm), st[t.a * 2] = true;
    }
    return 0;
}
posted @ 2020-08-06 10:44  Lngstart  阅读(66)  评论(0编辑  收藏  举报