Binary search template title and STL

Topic Source: https://www.51nod.com/Challenge/Problem.html#problemId=2063

Title Description

Enter an integer n and an integer n, n integers guarantee that has been sorted in ascending.
Then enter an integer q (q <= 100000) representative of q queries. Next q rows, each row contains an integer m, representative of a query. For each query, using a binary search is determined whether m n integers appeared in previous input. If present, the output line "Yes", otherwise a "No".

Entry

The first line: an integer n (n <= 100000). 
Next n lines, each line an integer ai (1 <= ai <= 10 ^ 9). 
The next line, an integer q. 
Next q lines each enter an integer x (1 <= x <= 10 ^ 9).

Export

q-line strings, each behavior "Yes" or "No".

SAMPLE INPUT

5
1
3
4
5
7
3
4
5
0

Sample Output

Yes
Yes
No

//方法一:手写bynary_seach
#include<bits/stdc++.h> using namespace std; const int max_n=1e5+10; int n, a[max_n], q, x; int main() { cin>>n; for(int i=0; i<n; i++) cin>>a[i]; cin>>q; for(int i=0; i<q; i++){ cin>>x; int low=0, high=n-1; bool f=0; while(low<=high){ int mid=high-(high-low)/2; if(a[mid]>x)high=mid-1; if(a[mid]<x)low=mid+1; if(a[mid]==x){ f=1; break; } } cout<<(f?"Yes":"No")<<endl; } return 0; }

 

//方法二:使用STL之bynary_seach()
#include<bits/stdc++.h>
using namespace std;
const int max_n=1e5+10;
int  n, a[max_n], q, x;
int main()
{
	cin>>n;
	for(int i=0; i<n; i++)
		cin>>a[i];
	cin>>q;
	for(int i=0; i<q; i++){
		cin>>x;
		int f=binary_search(a,a+n,x);
		cout<<(f?"Yes":"No")<<endl;
	}	
	return 0;
}

 

The STL binary search:

https://blog.csdn.net/zwj1452267376/article/details/47150521

Binary search in binary_search, lower_bound, upper_bound ( handwritten Detailed ):

https://blog.csdn.net/dl970220/article/details/80415798

C / C ++ - STL in lower_bound and upper_bound usage:

https://blog.csdn.net/jadeyansir/article/details/77015626

Guess you like

Origin www.cnblogs.com/tflsnoi/p/12288065.html