top1编程
← 返回题目
题解

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

1 条题解

  • 0
    @ 2026-10-21 1:03:43

    1. 解题思路

    有序集合维护库存,插入检测重复;取货时用lower_bound定位不短于需求的最短木材,与前驱比较,输出并删除更近者。

    2. 坑点和注意事项

    操作≤10^5,长度≤10^9。相同距离选较短;空仓和重复进货按指定文本输出。set支持动态前驱后继与删除,普通数组会退化O(q²)。

    3. 复杂度

    • 时间复杂度:O(q log q)。
    • 空间复杂度:O(q)。
    /*
    思路:有序集合维护库存,插入检测重复;取货时用lower_bound定位不短于需求的最短木材,与前驱比较,输出并删除更近者。
    关键规则与坑点:操作≤10^5,长度≤10^9。相同距离选较短;空仓和重复进货按指定文本输出。set支持动态前驱后继与删除,普通数组会退化O(q²)。
    时间复杂度:O(q log q)。空间复杂度:O(q)。
    */
    #include <bits/stdc++.h>
    using namespace std;
    int main()
    {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n;
        cin >> n;
        set<int> a;
        while (n--)
        {
            int op, x;
            cin >> op >> x;
            if (op == 1)
            {
                if (!a.insert(x).second)
                    cout << "Already Exist\n";
            }
            else if (a.empty())
                cout << "Empty\n";
            else
            {
                set<int>::iterator it = a.lower_bound(x);
                if (it == a.end())
                    --it;
                else if (it != a.begin() && x - *prev(it) <= *it - x)
                    --it;
                cout << *it << '\n';
                a.erase(it);
            }
        }
    }
    
    • 1