王道复试C语言 第八章搜索(上:广度优先搜索BFS)——代码笔记分享

结构体struct和类class

由于王道老师总是嘴上说着创建类,手上码着结构体,所以此处增加一个小知识。
类只有C++中有,而结构体有C和C++的区别。

struct Test {
   
   // 结构体
    // x 默认的访问属性为public
    int x;
};
class Test {
   
   // 类
    // x 默认的访问属性为private
    int x;
};

结构体与类的相同点: 均将多个相关的变量包装成为一个整体使用。

C和C++中结构体的区别: C 中结构体不能包含函数,C++ 的结构体可以包含函数

C++中的结构体与类的区别:

  1. class 中默认的成员访问权限是 private 的,而 struct 中则是 public 的;
  2. 从 class 继承默认是 private 继承,而从 struct 继承默认是 public 继承。

搜索

搜索:带有限制的枚举问题。
在这里插入图片描述

广度优先搜索 BFS

一层层访问,需设置辅助队列和辅助集合。
在这里插入图片描述

9.1Catch That Cow

使用广度优先算法 BFS 解决查找最优解的问题
在这里插入图片描述

北大OJ(我打不开)

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <queue>
using namespace std;
/*
Description:
Farmer John has been informed of the location of a fugitive逃跑的 cow and wants to catch her immediately. 
He starts at a point N (O <= N <= 100,000) on a number line and the cow is at a point K (0 <= K <= 100,000) on the same mumber line.
Farmer John has two modes of transportation: walking and teleporting.
1.Walking: FJ can move from any point X to the points X-l or X+l in a single minute.
2.Teleporting: FJ can move from any point X to the point 2*X in a single minute.
If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?

Input:
Line 1: Two space-separated integers: N and K.

Output:
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
*/
struct info {
   
   
	int pos;//位置
	int time;//到达目前位置所用时间
};
//使用广度优先算法 BFS 解决查找最优解的问题
int main() {
   
   
	int n, k;
	scanf("%d%d", &n, &k);
	queue<info> posQueue;//辅助队列
	bool isvisit[100001];//辅助数组
	for (int i = 0; i < 100001; i++) {
   
   
		isvisit[i] = false;
	}
	//把起始节点加入到队列
	info first;
	first.pos = n;
	first.time = 0;
	posQueue.push(first);
	while (!posQueue.empty()) {
   
   
		info cur = posQueue.front();//取队头节点
		posQueue.pop();

		//到达牛的位置
		if (cur.pos == k) {
   
   
			printf("%d\n", cur.time);//打印到达目前位置所用时间
			break;//结束
		}

		//没到牛的位置
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值