饭馆菜品选择问题
问题描述
小C来到了一家饭馆,这里共有 nn 道菜,第 ii 道菜的价格为 a_i。其中一些菜中含有蘑菇,s_i 代表第 ii 道菜是否含有蘑菇。如果 s_i = '1',那么第 ii 道菜含有蘑菇,否则没有。
小C希望点 kk 道菜,且希望总价格尽可能低。由于她不喜欢蘑菇,她希望所点的菜中最多只有 mm 道菜含有蘑菇。小C想知道在满足条件的情况下能选出的最小总价格是多少。如果无法按照要求选择菜品,则输出-1。
测试样例
样例1:
输入:`s = "001", a = [10, 20, 30], m = 1, k = 2`
输出:`30`
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
long solution(const std::string &s, const std::vector<int> &a, int m, int k) {
// 分类到两个向量中
vector<int> no_mogu;
vector<int> mogu;
for (size_t i = 0; i < s.size(); ++i) {
if (s[i] == '0') {
no_mogu.push_back(a[i]);
} else {
mogu.push_back(a[i]);
}
}
// 对两个向量进行排序
sort(no_mogu.begin(), no_mogu.end());
sort(mogu.begin(), mogu.end());
// cout<<"mogu"<<endl;
// std::cout << "Sorted vector: ";
// for (std::vector<int>::iterator it = no_mogu.begin(); it != no_mogu.end(); ++it) {
// std::cout << *it << " ";
// }
// std::cout << std::endl;
// std::cout << "mogu Sorted vector: ";
// for (std::vector<int>::iterator it = mogu.begin(); it != mogu.end(); ++it) {
// std::cout << *it << " ";
// }
// std::cout << std::endl;
// 计算结果
int ans = 0;
int i = 0, j = 0;
while (k > 0 && (i < no_mogu.size() || j < mogu.size())) {
// 优先从no_mogu中取值,直到用完或者数量达到m
if (i < no_mogu.size() && (j >= mogu.size() || j>=m || (j < m && no_mogu[i] <= mogu[j]))) {
ans += no_mogu[i++];
} else if (j < mogu.size() && j < m) { // 确保不超过m
ans += mogu[j++];
} else{
break;
}
--k;
}
// cout<<"ans:"<<ans<<endl;
// 如果k仍然大于0,说明无法选择足够的元素
if (k > 0) return -1;
return ans;
}
int main() {
std::cout << (solution("001", {10, 20, 30}, 1, 2) == 30) << std::endl;
std::cout << (solution("111", {10, 20, 30}, 1, 2) == -1) << std::endl;
std::cout << (solution("0101", {5, 15, 10, 20}, 2, 3) == 30) << std::endl;
std::cout << (solution("100111110010000", {3,4,9,13,16,4,3,9,1,11,7,7,4,4,11}, 1, 4) == 12) << std::endl;
return 0;
}