P5250 【深基17.例5】木材仓库【set+二分】

题目

https://www.luogu.com.cn/problem/P5250

 思路

使用set在寻找合适的木头的时候使用二分,但是一个set使用好像不能同时使用lower_bound(a)与lower_bound(a,greater<int>())?

于是菜菜的使用lower_bound找到大于等于的再往前找了…………

注意set中的lower_bound函数与普通数组的lower_bound函数的使用方法的区别

代码

#include<iostream>
#include<cstdio>
#include<set>
#include<algorithm>
#include<functional>
#include<cmath>
using namespace std;
set<int>list;
int main()
{
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
    {
        int a, b;
        scanf("%d%d", &a, &b);
        if (a == 1)
        {
            if (list.find(b) != list.end())printf("Already Exist
");
            else list.insert(b);
        }
        else
        {

            if (list.empty()) { printf("Empty
"); continue; }
            set<int>::iterator i = list.lower_bound(b); //查询前驱后继
            set<int>::iterator j = i;
            if (j != list.begin()) j--;
            if (i != list.end() && b - (*j)>(*i) - b) j = i; //比较
            printf("%d
",*j); //输出
            list.erase(j); //删除
            
        }
    }

}
原文地址:https://www.cnblogs.com/Jason66661010/p/13205123.html