7.25 binary search template

  Today, as we organize a class classic title - half the problem, such problems often increase in the popularity of the group competition, and often appear as a difficulty, it is necessary to lay the foundation for the students at the beginning of the contact, skilled use of templates , after the race we can do Shoudaoqinlai.

Title Description

 

 

 

Solution to a problem Code:

#include<iostream>
#include<string>
using namespace std;
int n,m;
//找出小于等于该值的最大值
long long a[100005],b[50005];
/*
bool binary_search(long long value){
 int l=0,r=n-1;
 while(l<r){
  int mid=(l+r+1)/2;
  if(a[mid]<=value){
   l=mid;
  }
  else{
   r=mid-1;
  }
 }
 if(a[l]==value)
 {
  return true;
 }
 return false;
}
*/
//找出大于等于的最小值
bool binary_search(long long value){
 int l=0,r=n-1;
 while(l<r){
  int mid=(l+r)/2;
  if(a[mid]>=value){
   r=mid;
  }
  else{
   l=mid+1;
  }
 }
 if(a[r]==value){
  return true;
 }
 return false;
}
int main(){
 scanf("%d",&n);
 for(int i=0;i<n;i++){
  scanf("%lld",&a[i]);
 }
 scanf("%d",&m);
 for(int i=0;i<m;i++){
  scanf("%lld",&b[i]);
 }
 int ans=0;
 for(int i=0;i<m;i++){
  bool flag=binary_search(b[i]);
  if(flag==true){
   ans++;
  }
 }
 printf("%d",ans);
 return 0;
}

 

Guess you like

Origin www.cnblogs.com/cxs070998/p/11243396.html