首先介紹c++萬能頭文件c++
#include<bits/stdc++.h>算法
using namespace std;(比較適合偷懶,可是不能確保不會出錯)(用仍是能夠的,粗錯了再回頭來改嘛)owo數組
接下來介紹一下兩個二分查找函數;函數
upper_bound()與lower_bound();spa
ForwardIter lower_bound(ForwardIter first, ForwardIter last,const _Tp& val)算法(函數)返回一個非遞減序列[first, last)中的第一個大於等於值val的地址.net
ForwardIter upper_bound(ForwardIter first, ForwardIter last, const _Tp& val)算法(函數)返回一個非遞減序列[first, last)中的第一個大於值val的地址code
參考:https://blog.csdn.net/zyq_19960204/article/details/49516981blog
upper_bound(r,l,key)排序
r:表明數組中的首地址;l表明數組的末尾地址;key表明咱們要查找的那個數值;it
upper_bound反回的是數組中(排序完成的數列)大於key的那個數據的地址;
同理lower_bound返回的是大於等於key的那個數據的地址。
參考:https://blog.csdn.net/sdz20172133/article/details/80101838
例題:入門基礎之二分查找
數組a[]有n個元素,元素值保證不降(即數組知足a1<=a2<=a3<=…<=ak<=…<=an )。
你的任務是,找到數組中大於數字key的全部元素中最小的那個。
如:每組第一排有兩個數字n,m,分別表明數組的元素個數和詢問的次數。(1<=n,m<=10^5)
第二排有n個整數,表示數組的n個元素的值。(1<=ai<=10^5)
接下來有m排,每排有一個整數key(1<=key<=10^5)若是沒有所求key值用-1代替;
#include<bits/stdc++.h> using namespace std; int main() { int n,m; while(scanf("%d %d",&n,&m)!=EOF) { int a[100002]; for(int i=0;i<n;i++) scanf("%d",&a[i]); while(m--) { int key,ans=-1; scanf("%d",&key); if((upper_bound(a,a+n,key)-a)>n-1) printf("%d\n",ans); else printf("%d\n",*upper_bound(a,a+n,key)); } } return 0; }