Catch That Cow(队列)

本文介绍了一道来自HDU在线评测系统的题目,并通过使用BFS(宽度优先搜索)算法来解决该问题。文章展示了完整的C++代码实现,包括节点结构定义、宽度优先搜索函数以及主函数中的输入输出处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  题目  ;http://acm.hdu.edu.cn/showproblem.php?pid=2717

#include <iostream>
#include <cstring>
#include<cstdio>
#include <stack>
#include <queue>
#include <map>
#include <algorithm>
using namespace std;
int vis[100001];
int n, m;
int ans;
struct node {
	int x, step;
};
int bfs() {
	queue<node>q;
	while (!q.empty()) {
		q.pop();
	}
	node now, next;
	now.x = n;
	now.step = 0;
	vis[now.x] = 1;
	q.push(now);
	while (!q.empty()) {
		now = q.front();
		q.pop();
		for (int i = 0; i < 3; i++) {
			if (i == 0) {
				next.x = now.x - 1;
			}
			else if (i == 1) {
				next.x = now.x + 1;
			}
			else if (i == 2) {
				next.x = now.x * 2;
			}
			next.step = now.step + 1;
			if (next.x == m) {
				return next.step;
			}
			if (!vis[next.x] && next.x >= 0 && next.x <= 100001) {
				q.push(next);
				vis[next.x] = 1;
			}
		}
	}
}
int main() {
	cin >> n >> m;
	memset(vis, 0, sizeof(vis));
	if (n >= m) {
		cout << n - m << endl;
	}
	cout << bfs() << endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值