第9课:二分查找 @200班

潘CSP200班

2025-01-12 9:59:15
2025-01-31 19:36:15

信息与公告

1、二分查找两种方法:

lower_bound(a+1, a+n+1, x)-a:在数组a中查找大于等于x的第1个数的下标。  
upper_bound(a+1, a+n+1, x)-a:在数组a中查找大于x的第1个数的下标。

2、lower_bound和upper_bound使用技巧:

查找>=x的第1个位置,用lower_bound
查找==x的第1个位置,用lower_bound
查找<x的最后1个位置,用lower_bound(需-1)
查找>x的第1个位置,用upper_bound
查找==x的最后1个位置,用upper_bound(需-1)
查找<=x的最后1个位置,用upper_bound(需-1)

3、用二分查找优化枚举

优化思想1:将枚举两个数的问题,优化为:枚举1个数 和 二分查找1个数的问题。
状态 题目 统计
统计公平数对的数目 4 / 4 / 4
学生和导师 4 / 4 / 4
A-B 数对 6 / 7 / 8
递增三元组 4 / 5 / 5