【求助】
  • 板块学术版
  • 楼主幸存者
  • 当前回复6
  • 已保存回复6
  • 发布时间2021/12/19 12:48
  • 上次更新2023/10/28 14:05:58
查看原帖
【求助】
549357
幸存者楼主2021/12/19 12:48

题目描述:

农夫知道一头牛的位置,想要抓住它。农夫和牛都位于数轴上,农夫起始位于点 N(0N105)N(0 \le N \le 10^5),牛位于点 K(0K105)K(0 \le K \le 10^5)。农夫有两种移动方式:

  1. XX 移动到 x1x-1x+1x+1,每次移动花费一分钟。
  2. XX 移动到 2×X2\times X,每次移动花费一分钟。

假设牛没有意识到农夫的行动,站在原地不动。农夫最少要花多少时间才能抓住牛?

我的代码:

#include <iostream>
#include <queue>
using namespace std;
int n, k, dis[100010];
bool vis[100010];
int bfs()
{
	queue<int> q;
	q.push(n);
	vis[n] = true;
	while (!q.empty())
	{
		int x = q.front();
		if (x == k) return dis[x];
		q.pop();
		int y = x - 1;
		if (!vis[y])
		{
			q.push(y);
			vis[y] = true;
			dis[y] = dis[x] + 1;
		}
		y = x + 1;
		if (!vis[y])
		{
			q.push(y);
			vis[y] = true;
			dis[y] = dis[x] + 1;
		}
		y = 2 * x;
		if (!vis[y])
		{
			q.push(y);
			vis[y] = true;
			dis[y] = dis[x] + 1;
		}
	}
}
int main()
{
	int n, k;
	cin >> n >> k;
	cout << bfs() << endl;
	return 0;
}

请问我哪里错了???

2021/12/19 12:48
加载中...