P5250 木材仓库【set】

【深基17.例5】木材仓库

题目描述

博艾市有一个木材仓库,里面可以存储各种长度的木材,但是保证没有两个木材的长度是相同的。作为仓库负责人,你有时候会进货,有时候会出货,因此需要维护这个库存。有不超过 100000 条的操作:

  • 进货,格式1 Length:在仓库中放入一根长度为 Length(不超过 1 0 9 10^9 109) 的木材。如果已经有相同长度的木材那么输出Already Exist
  • 出货,格式2 Length:从仓库中取出长度为 Length 的木材。如果没有刚好长度的木材,取出仓库中存在的和要求长度最接近的木材。如果有多根木材符合要求,取出比较短的一根。输出取出的木材长度。如果仓库是空的,输出Empty

输入格式

输出格式

样例 #1

样例输入 #1

7
1 1
1 5
1 3
2 3
2 3
2 3
2 3

样例输出 #1

3
1
5
Empty

问题链接: P5250 木材仓库
问题分析: 集合问题,不解释。
参考链接: (略)
题记: (略)

AC的C++语言程序如下:

/* P5250 木材仓库 */

#include <iostream>
#include <set>

using namespace std;

int main()
{
    
    
    set<int> st;
    int n;
    cin >> n;
    while (n--) {
    
    
        int op, len;
        cin >> op >> len;
        if (op == 1) {
    
    
            if (st.count(len))
                cout << "Already Exist" << endl;
            else
                st.insert(len);
        } else if (op == 2) {
    
    
            if (st.size() == 0) {
    
    
                cout << "Empty" << endl;
            } else {
    
    
                set<int>::iterator it = st.lower_bound(len);
                if (it == st.begin()) {
    
    
                    cout << *it << endl;
                    st.erase(it);
                } else if(it == st.end()) {
    
    
                    cout << *(--it) << endl;
                    st.erase(it);
                } else {
    
    
                    int x = *it;
                    int y = *(--it);
                    if (x - len < len - y) {
    
    
                        cout << x << endl;
                        st.erase(++it);
                    } else {
    
    
                        cout << y << endl;
                        st.erase(it);
                    }
                }
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/tigerisland45/article/details/141176439