Files
python/TangDou/AcWing/MiniPath/1100.md
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

83 lines
1.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## [$AcWing$ $1100$. 抓住那头牛](https://www.acwing.com/problem/content/1102/)
### 一、题目描述
农夫知道一头牛的位置,想要抓住它。
农夫和牛都位于数轴上,农夫起始位于点 $N$,牛位于点 $K$。
农夫有两种移动方式:
从 $X$ 移动到 $X−1$ 或 $X+1$,每次移动花费一分钟
从 $X$ 移动到 $2∗X$,每次移动花费一分钟
假设牛没有意识到农夫的行动,站在原地不动。
农夫 **最少** 要花多少时间才能抓住牛?
**输入格式**
共一行,包含两个整数$N$和$K$。
**输出格式**
输出一个整数,表示抓到牛所花费的 **最少时间** 。
**数据范围**
$0≤N,K≤10^5$
**输入样例**:
```cpp {.line-numbers}
5 17
```
**输出样例**:
```cpp {.line-numbers}
4
```
### 二、实现代码
```cpp {.line-numbers}
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
const int INF = 0x3f3f3f3f;
int n, k;
int q[N];
int dist[N];
int Min = INF;
int bfs() {
//初始化距离数组-1
memset(dist, -1, sizeof dist);
int hh = 0, tt = -1;
q[++tt] = n; //加入起点n
dist[n] = 0; // n距离出发点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 0;
}
int main() {
//农夫起始位于点N,牛位于点K
cin >> n >> k;
printf("%d\n", bfs());
return 0;
}
```
### 三、总结
蓝桥杯青少组初赛原题,同类题比如 [奇怪的电梯](https://www.luogu.com.cn/problem/P1135)