zoukankan      html  css  js  c++  java
  • lower_bound &&upper_bound

    lower_bound( )和upper_bound( )都是利用二分查找的方法在一个排好序的数组中进行查找的。

    在从小到大的排序数组中,

    lower_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

    upper_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

    在从大到小的排序数组中,重载lower_bound()和upper_bound()

    lower_bound( begin,end,num,greater<type>() ):从数组的begin位置到end-1位置二分查找第一个小于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

    upper_bound( begin,end,num,greater<type>() ):从数组的begin位置到end-1位置二分查找第一个小于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。

    功能:函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置.

    注意:如果所有元素都小于val,则返回last的位置,且last的位置是越界的!!

    功能:函数upper_bound()返回的在前闭后开区间查找的关键字的上界,返回大于val的第一个元素位置

    注意:返回查找元素的最后一个可安插位置,也就是“元素值>查找值”的第一个元素的位置。同样,如果val大于数组中全部元素,返回的是last。(注意:数组下标越界)

            lower_bound(val):返回容器中第一个值【大于或等于】val的元素的iterator位置。

            upper_bound(val): 返回容器中第一个值【大于】

    #include <iostream>
    #include <algorithm>
    using namespace std;
    typedef long long ll;
    inline ll read(){
        ll x=0,f=1; char ch=getchar();
        while(!isdigit(ch)) ch=='-'&(f=-1),ch=getchar();
        while(isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=getchar(); return x*f;
    }
    int n;
    const int N=1<<20;
    int a[N];
    signed main(){
        n=read();
        for(register int i=1;i<=n;i++) a[i]=read();
        sort(a+1,a+n+1);
        int find=read();
        int l=lower_bound(a+1,a+n+1,find)-a;
        int r=upper_bound(a+1,a+n+1,find)-a;
        cout<<l<<' '<<r<<endl;
        return 0;
    }

     

    不存在十全十美的文章 如同不存在彻头彻尾的绝望
  • 相关阅读:
    web.xml中<security-constraint>安全认证标签说明
    TPS与QPS
    Idea无法加载主类
    动态历史
    领导之路
    aven依赖分析,jar包冲突解决利器intellij idea插件Maven Helper强烈建议安装
    Maven 电脑每次重启 mvn -v 都显示 不是命令
    IntelliJ IDEA 最新版 2019.1 安装与激活
    @Param注解的使用
    Mybatis通用Mapper介绍与使用
  • 原文地址:https://www.cnblogs.com/qf-breeze/p/10350032.html
Copyright © 2011-2022 走看看