搜索(c++)

二分查找

# include <iostream>
# include <algorithm>
# include <cmath>
# include <string>
# include <cstring>
using namespace std;
int main(){
	int m , n , x;
	cin >> n >> m ;
	int a[1000];
	for (int i = 0 ; i < n ; i++)
		cin >> a[i];
	while (m -- ){
		cin >> x; 
		int left = 0 ,right = n ;
		while (left < right ){
			int mid = (left + right ) / 2;
			if (a[mid] >= x)
				right = mid ;
			else left = mid + 1;
		}
		if (a[left]!=x){
			cout << " no "<< endl;		
			continue;
		}
		cout << left << endl;
		
	}
	return 0  ;
}

lower_bound 和 upper_bound 在algorithm 头文件中 利用 二分查找 对有序数组进行查找

lower_bound 会返回数组中大于等于 被查数 的 地址 , 查找坐标即  -a

upper_bound 返回数组 小于 被查数 的地址 ,查找坐标 -a 

# include <iostream>
# include <algorithm>
# include <cmath>
# include <string>
# include <cstring>
using namespace std;
const int N = 2000000;
int main(){
	int m , n , x;
	cin >> n >> m ;
	int a[1000];
	int b[1000];
	for (int i = 0 ; i < n ; i++)
		cin >> a[i];
	int cnt = 0 ; 
	sort (a, a+n );
	while ( m -- ){
		cin >> x ;
		int t1 = upper_bound(a,a+n,x) - a ;//找出 数组中 第一个小于被查数x的坐标 
		int t2 = lower_bound(a,a+n,x) - a; // 找出数组中第一个大于或等于 被查数的坐标
	cout << a[t1] << endl ;
	cout << a[t2] << endl ;
}
	return 0  ;
}

 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
宽度优先搜索(BFS)是一种图遍历算法,可以用来解决很多问题,比如最短路径、连通性、拓扑排序等等。以下是一个简单的宽度优先搜索C++ 实现: ```c++ #include <iostream> #include <queue> #include <vector> using namespace std; const int MAXN = 100; // 最大节点数 vector<int> adj[MAXN]; // 邻接表 bool vis[MAXN]; // 是否访问过 void bfs(int s) { queue<int> Q; // 存放节点的队列 Q.push(s); // 将起点加入队列 vis[s] = true; // 标记起点已被访问 while (!Q.empty()) { // 只要队列不空,就一直搜索 int x = Q.front(); // 取出队首节点 Q.pop(); // 弹出队首节点 for (int i = 0; i < adj[x].size(); i++) { // 枚举与 x 相邻的节点 int y = adj[x][i]; if (!vis[y]) { // 如果 y 没有被访问过 Q.push(y); // 将 y 加入队列 vis[y] = true; // 标记 y 已被访问 } } } } int main() { int n, m; cin >> n >> m; // 输入节点数和边数 for (int i = 1; i <= m; i++) { int x, y; cin >> x >> y; // 输入一条边的两个端点 adj[x].push_back(y); // 存储邻接表 adj[y].push_back(x); } for (int i = 1; i <= n; i++) { if (!vis[i]) { // 如果 i 没有被访问过 bfs(i); // 从 i 开始搜索连通块 } } return 0; } ``` 在这个实现中,我们使用邻接表来存储图,使用一个 bool 数组来标记每个节点是否被访问过,使用一个 queue 来存放待搜索的节点。首先,我们从起点开始搜索,将起点加入队列并标记为已访问。然后,只要队列不空,就不断取出队首节点 x 并枚举与 x 相邻的节点 y。如果 y 没有被访问过,我们就将 y 加入队列并标记为已访问。这样,我们就可以搜索出从起点能够到达的所有节点了。如果图不连通,我们需要对每个没有被访问过的节点都进行一次搜索,这样就可以找到所有连通块了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值