洛谷刷题C++语言 | P5250 木材仓库

​学习C++从娃娃抓起!记录下洛谷C++学习和备考过程中的题目,记录每一个瞬间。

附上汇总贴:洛谷刷题C++语言 | 汇总


【题目描述】

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

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

【输入】

【输出】

【输入样例】

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

【输出样例】

3
1
5
Empty

【代码详解】

在这里插入图片描述

#include <bits/stdc++.h>
using namespace std;
int n, type, length;
set<int> a;
set<int>::iterator it, itup;
int main()
{
    // ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    cin >> n;
    for (int i=0; i<n; i++) {
        cin >> type >> length;
        it = find(a.begin(), a.end(), length);
        if (type==1) {
            if (it==a.end()) a.insert(length);
            else cout << "Already Exist" << endl;
        } else if (type==2) {
            if (a.empty()) cout << "Empty" << endl;
            else if (it!=a.end()) {
                cout << length << endl;
                a.erase(it);
            } else {
                itup = upper_bound(a.begin(), a.end(), length);
                if (itup==a.end()) {
                    itup--;
                    cout << *itup << endl;
                    a.erase(itup);
                } else if (itup==a.begin()) {
                    cout << *itup << endl;
                    a.erase(itup);
                } else {
                    itup--;
                    it = itup++;
                    if (length-*it <= *itup-length) {
                        cout << *it << endl;
                        a.erase(it);
                    } else {
                        cout << *itup << endl;
                        a.erase(itup);
                    }
                }
            }
        }
    }
    return 0;
}

【运行结果】

7
1 1
1 5
1 3
2 3
3
2 3
1
2 3
5
2 3
Empty
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值