36.饭馆菜品选择问题 + 37.构造回文字符串问题(C++)

#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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值