The use of STL binary search

STL binary search

Use object: ordered array

Header file: algorithm

The return value of lower_bound() is an iterator, returning to the position of the first value greater than or equal to the key
. The array boundary a in the function parameter, a+8 is left closed and right open. The address after the search fails (out-of-bounds address)

    #include <algorithm>
    #include <iostream>
    using namespace std;
    int main()
    {
    
    
    	int a[]={
    
    1,2,3,4,5,7,8,9};
    	printf("%d",lower_bound(a,a+8,6)-a); 
    	
     return 0;	
    } 

Output: 5

Change key to 10, all vals are less than key, return the position of last

#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
    
    
	int a[]={
    
    1,2,3,4,5,7,8,9};
	printf("%d",lower_bound(a,a+8,10)-a); 
	
 return 0;	
} 

Output: 8

upper_bound() function, it returns the last element greater than or equal to key

Example : CF1077E
AC code:

#include <bits/stdc++.h>
using namespace std;

const int maxn = 1e6 + 7;

int a[maxn];
map<int, int> mp;

int main()
{
    
    
	int n;
	scanf("%d",&n);
	int cnt=0,x;
	for(int i=1;i<=n;i++)
    {
    
    
		scanf ("%d",&x);
		if(!mp[x])
		{
    
    
			mp[x]=++cnt;
		}
		++a[mp[x]];
	}
	sort(a+1,a+cnt+1);
	int sum=0;
	for(int j=1;j<=n;++j)
    {
    
    
		int m=0;
		int l=1;
		for (int k=j;k<=n;k*=2)
        {
    
    
			int p=lower_bound(a+l,a+cnt+1,k)-a;
			if(p==cnt+1)
                break;
            m+=k;
			l=p+1;
		}
		sum=max(sum,m);
	}
	printf ("%d\n",sum);
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_40534166/article/details/97633356