AcWing 1100. 抓住那头牛(搜索)

题目链接


题目描述

农夫知道一头牛的位置,想要抓住它。
农夫和牛都位于数轴上,农夫起始位于点 N,牛位于点 K。
农夫有两种移动方式:

  1. 从 X 移动到 X−1 或 X+1,每次移动花费一分钟
  2. 从 X 移动到 2∗X,每次移动花费一分钟
    假设牛没有意识到农夫的行动,站在原地不动。
    农夫最少要花多少时间才能抓住牛?

题目代码

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

using namespace std;

const int N = 100010;

int n, k;
int q[N];
int dist[N];

int bfs()
{
    memset(dist, -1, sizeof dist);
    dist[n] = 0;
    q[0] = n;
    
    int hh = 0, tt = 0;
    
    while(hh <= tt)
    {
        int t = q[hh ++ ];
        
        if(t == k) return dist[k];
        
        if(t + 1 < N && dist[t + 1] == -1)
        {
            dist[t + 1] = dist[t] + 1;
            q[ ++ tt] = t + 1;
        }
        if(t - 1 >= 0 && dist[t - 1] == -1)
        {
            dist[t - 1] = dist[t] + 1;
            q[ ++ tt] = t - 1;
        }
        if(t * 2 < N && dist[t * 2] == -1)
        {
            dist[t * 2] = dist[t] + 1;
            q[ ++ tt] = t * 2;
        }
    }
    
    return -1;
}

int main()
{
    cin >> n >> k;
    
    cout << bfs() << endl;
    
    return 0;
}
posted @ 2022-07-12 11:19  esico  阅读(30)  评论(0)    收藏  举报