邻值查找——stl函数lower_bound和upper_bound的使用

邻值查找

stl set 动态维护有序序列

  1. lower_bound >=x的最小的数
  2. upper_bound >x的最小的数

这两个函数返回的是迭代器

大于Ai最小的数:it=upper_bound(Ai)

小于Ai最大的数:it--;

注意哨兵的设置 因为大于x最小的数,需要一个值

#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
#include <set>
#include <cmath>
#include <algorithm>
#include <cstdio>
#include <limits.h>
using namespace std;

int main()
{
    int n;
    cin>>n;
    set<pair<int,int>> s;
    s.insert({INT_MAX,0});//设置哨兵
    s.insert({INT_MIN,0});

    for(int i=1;i<=n;i++)
    {
        int v;
        cin>>v;
        if(i>1)
        {
            auto it=s.upper_bound({v,0});//pair可以用{}
            auto jt=it;
            jt--;
            long long rv=it->first-(long long)v,lv=(long long)v-jt->first;
            if(lv<=rv) cout<<lv<<' '<<jt->second<<endl;
            else
                cout<<rv<<' '<<it->second<<endl;
        }
        s.insert({v,i});
    }
    return 0;
}

 

posted on 2019-04-18 14:09  kelly1895  阅读(240)  评论(0编辑  收藏  举报

导航