36. 饭馆菜品选择问题 | 豆包 MarsCode 刷题

57 阅读1分钟

这不是排个序之后按顺序选就完了吗?

时间复杂度:Θ(nlogn)\Theta(n\log n)
空间复杂度:Θ(n)\Theta(n)

代码(C++):

#include <vector>
#include <string>
#include <utility>
#include <algorithm>

using namespace std;

long solution(const std::string& s, const std::vector<int>& a, int m, int k) {
    vector<pair<int, char>> b;
    for (size_t i = 0; i < a.size(); ++i) {
        b.push_back(make_pair(a[i], s[i]));
    }
    sort(b.begin(), b.end());
    long ans = 0;
    for (const auto& x : b) {
        if (k == 0) {
            break;
        }
        if (x.second == '1') {
            if (m > 0) {
                --m;
                --k;
                ans += x.first;
            }
        } else {
            --k;
            ans += x.first;
        }
    }
    return k > 0 ? -1 : ans;
}