STL中的二分查找——lower_bound 、upper_bound 、binary_search

来源:互联网 发布:剑三清冷萝莉捏脸数据 编辑:程序博客网 时间:2024/05/16 01:19

       二分查找很简单,原理就不说了。STL中关于二分查找的函数有三个lower_bound 、upper_bound 、binary_search 。这三个函数都运用于有序区间(当然这也是运用二分查找的前提)。

       其中如果寻找的value存在,那么lower_bound返回一个迭代器指向其中第一个这个元素。upper_bound返回一个迭代器指向其中最后一个这个元素的下一个位置(明确点说就是返回在不破坏顺序的情况下,可插入value的最后一个位置)。如果寻找的value不存在,那么lower_bound和upper_bound都返回“假设这样的元素存在时应该出现的位置”。要指出的是lower_bound和upper_bound在源码中只是变换了if—else语句判定条件的顺序,就产生了最终迭代器位置不同的效果。

       binary_search试图在已排序的[first,last)中寻找元素value,若存在就返回true,若不存在则返回false。返回单纯的布尔值也许不能满足需求,而lower_bound、upper_bound能提供额外的信息。事实上由源码可知binary_search便是利用lower_bound求出元素应该出现的位置,然后再比较该位置   的值与value的值。该函数有两个版本一个是operator< ,另外一个是利用仿函数comp进行比较。


#include <iostream>#include <stdio.h>#include <algorithm>//必须包含的头文件using namespace std;int main(){ int point[10] = {1,3,7,7,9}; int tmp = upper_bound(point, point + 5, 7) - point;//按从小到大,7最多能插入数组point的哪个位置 printf("%d\n",tmp); tmp = lower_bound(point, point + 5, 7) - point;////按从小到大,7最少能插入数组point的哪个位置 printf("%d\n",tmp); return 0;}output:42

 逆序数
在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序。一个排列中逆序的总数就称为这个排列的逆序数。
如2 4 3 1中,2 1,4 3,4 1,3 1是逆序,逆序数是4。给出一个整数序列,求该序列的逆序数。
Input
第1行:N,N为序列的长度(n <= 50000)第2 - N + 1行:序列中的元素(0 <= A[i] <= 10^9)
Output
输出逆序数
Input示例
42431
Output示例
4

#include<cstdio>#include<cstring>#include<vector>#include<algorithm>using namespace std;int n;vector<int > shu;int main(){    scanf("%d",&n);    long long s=0,a;    int kk[60000];    for (int i=0;i<n;i++)    {        scanf("%d",&kk[i]);        s+=shu.end()-upper_bound(shu.begin(), shu.end(),kk[i]);        shu.insert(upper_bound(shu.begin(), shu.end(),kk[i]),kk[i]);    }    printf("%lld\n",s);    return 0;}


0 0
原创粉丝点击