1 条题解

  • 0
    @ 1970-2-16 20:40:53

    【例56.2】 购买饮料

    解题思路

    将店铺价格升序排序。每次预算x,用upper_bound找到首个大于x的位置,其前面元素数量就是可选店数。

    正确性说明

    按顺序完成所述运算后,每个输入元素都被处理在相应位置或统计项中。保存的中间状态与已处理数据对应,最终输出与题目定义一致。

    易错点

    价格等于预算可以买,所以用upper_bound而非lower_bound。

    复杂度

    时间O(n log n+m log n),空间O(n)。

    参考代码(C++11)

    #include <bits/stdc++.h>
    using namespace std;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n, m;
        cin >> n >> m;
        vector<int> a(n);
        for (int &x : a)
            cin >> x;
        sort(a.begin(), a.end());
        while (m--) {
            int x;
            cin >> x;
            cout << upper_bound(a.begin(), a.end(), x) - a.begin() << "\n";
        }
        return 0;
    }
    
    • 1

    信息

    ID
    374
    时间
    1000ms
    内存
    64MiB
    难度
    普及−
    标签
    递交数
    1
    已通过
    1
    上传者