结构体struct和类class
由于王道老师总是嘴上说着创建类,手上码着结构体,所以此处增加一个小知识。
类只有C++中有,而结构体有C和C++的区别。
struct Test {
// 结构体
// x 默认的访问属性为public
int x;
};
class Test {
// 类
// x 默认的访问属性为private
int x;
};
结构体与类的相同点: 均将多个相关的变量包装成为一个整体使用。
C和C++中结构体的区别: C 中结构体不能包含函数,C++ 的结构体可以包含函数
C++中的结构体与类的区别:
- class 中默认的成员访问权限是 private 的,而 struct 中则是 public 的;
- 从 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;//结束
}
//没到牛的位置