#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <limits> // 添加头文件以使用 std::numeric_limits
using namespace std;
long solution(const std::string& s, const std::vector<int>& a, int m, int k) {
// 将菜品分为含有蘑菇和不含有蘑菇两类
std::vector<int> mushroomPrices;
std::vector<int> noMushroomPrices;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '1') {
mushroomPrices.push_back(a[i]);
} else {
noMushroomPrices.push_back(a[i]);
}
}
// 对两类菜品的价格进行排序
std::sort(mushroomPrices.begin(), mushroomPrices.end());
std::sort(noMushroomPrices.begin(), noMushroomPrices.end());
int price = 0;
int i = 0, j = 0;
// 优先选择价格较低的菜品
while (k > 0 && (i < mushroomPrices.size() || j < noMushroomPrices.size())) {
if (i < mushroomPrices.size() && (j == noMushroomPrices.size() || mushroomPrices[i] < noMushroomPrices[j]) && m > 0) {
price += mushroomPrices[i++];
m--;
k--;
} else if (j < noMushroomPrices.size()) {
price += noMushroomPrices[j++];
k--;
} else {
break; // 无法选择更多菜品
}
}
// 检查是否成功选择了 k 道菜
return k == 0 ? price : -1;
}
int main() {
std::cout << (solution("001", {10, 20, 30}, 1, 2) == 30) << std::endl; // 应输出 1
std::cout << (solution("111", {10, 20, 30}, 1, 2) == -1) << std::endl; // 应输出 1
std::cout << (solution("0101", {5, 15, 10, 20}, 2, 3) == 30) << std::endl; // 应输出 1
return 0;
}
策略优选价格少的。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
std::string solution(const std::string& s) {
// PLEASE DO NOT MODIFY THE FUNCTION SIGNATURE
// write code here
std::string ans = s;
for(int i = 0;i< s.size()/2;i++){
ans[s.size() -1 - i] = s[i];
}
if(ans < s){
return ans;
}
for(int i = (s.size()-1)/2; i>=0 ;i--){
if(ans[i] > 'a'){
ans[i] = ans[i] - 1;
ans[ans.size() -1 -i] = ans[i];
return ans;
}else{
ans[i] = 'z';
ans[ans.size() -1 -i] = ans[i];
}
}
return "-1";
}
int main() {
std::cout << (solution("abc") == "aba") << std::endl;
std::cout << (solution("cba") == "cac") << std::endl;
std::cout << (solution("aaa") == "-1") << std::endl;
return 0;
}
先对称一下之后先处理中间的倘若遇到‘a’则改写为‘z’当若已知都是‘a’会返回“-1”;
不是‘a’时则减少1.