跳到正文

个人记录

二分学习笔记

GraceZy约 3 分钟
原文

这是 2025年11月13日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2022年6月5日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

先来玩个游戏,1~100之间我想一个数,猜一猜我想的是多少,可以问我几个问题,我回答是或不是

相信大家都玩过,那么应该如何问问题呢

思路:

对a从小到大排序 追加 a [0] 和 a[n+1](超小和超大)

在a中找x可化为找 a[i-1] < x <= a[i] 的下标i

初始:a[0] < x <= a[n+1]

我们用l和r记区间的上下限的下标

每次判断中点的x的大小

while(r-l>1)

mid=(l+r)/2

若a[mid] < x,l = mid

否则 r = mid

当while结束时,l+1 = r

a[r-1] < x <= a[r], 此时判 a[r] 是否等于x

代码实现(手写版):

C++
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
long long n,Q,a[100005];
bool check(long long x){
	int l=0,r=n+1,mid;
	while(r-l>1){
		mid=(l+r)/2;
		if(a[mid]<x) l=mid;
		else r=mid;
	}
	if(a[r]==x) return true;
	return false;
}
int main(){
	cin>>n>>Q;
	for(int i = 1;i <= n;i++){
		cin>>a[i];
	}
	sort(a+1,a+1+n);
	a[n+1]=2e18;
	while(Q--){
		long long b;
		cin>>b;
		if(check(b)) cout<<"Yes"<<endl;
		else cout<<"No"<<endl;
	}
	return 0;
}

内置函数:

lower_bound函数

可以找出数组中最靠前的>=给定值的元素的地址

数组必须是从小到大排好序的!!!

在 a[1] 至 a[n] 中找最靠前的 a[i] >= x

int p=lower_bound(a+1,a+1+n,x)-a;

lower_bound只能找到下标,需要减去下标(数组名)才是地址

若找不到 返回 a[n+1] 的地址

代码实现(函数版):

C++
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
long long n,Q,a[100005];
int main(){
	cin>>n>>Q;
	for(int i = 1;i <= n;i++){
		cin>>a[i];
	}
	sort(a+1,a+1+n);
	while(Q--){
		long long b;
		cin>>b;
		int p=lower_bound(a+1,a+1+n,b)-a;
		if(a[p]==b) cout<<"Yes"<<endl;
		else cout<<"No"<<endl;
	}
	return 0;
}

upper_bound函数

第一个大于x的位置

(那么最后,你猜出我想的那个数是多少了嘛)