二分查找函数

有两个函数

lower_bound:查找大于等于x的最小值所在地址

upper_bound:查找大于x的最小值所在地址

这两个函数都在头文件

#include<algorithm>

 em事实上并不太用vector,之前的经历让我对它没有什么太大的好感,虽然不排斥

冲着书想了想,感觉vector的有点麻烦,况且马上就AFO了,就不弄了

代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#define NUM 1000010
#define FOR(a,b,c) for( int a = b;a <= c;a++ )
using namespace std;

int n,m;
int a[NUM];

int main(){
    
    cin >> n >> m;
    FOR( i,1,n )
        cin >> a[i];
    int x;
    FOR( i,1,m ){
        cin >> x;
        int p = lower_bound( a+1,a+n+1,x )-a;
        if( a[p] == x ) cout << p << " ";
        else cout << -1 << " ";
    }
    
    return 0;
}
lower_bound

刚才又试了试upper_bound,感觉不如lower_bound好使,心里有数

附:

果然这个博客不是最后一篇啊(笑)

一会可能还会写几份板子的博客

NOIP RP++

posted @ 2022-11-25 16:32  little_sheep_xiaoen  阅读(13)  评论(0编辑  收藏  举报