华为od机试统一考试B卷 C++【雨花石难题】

题目

在这里插入图片描述

代码

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int checkSplit(int stoneCount, vector<int>& stoneWeights) {
    int totalWeight = 0;

    // 计算所有雨花石的总重量
    for (int weight : stoneWeights) {
        totalWeight += weight;
    }

    // 如果重量之和不能被2整除,则不可能平分
    if (totalWeight % 2 != 0) {
        return -1;
    }

    int halfWeight = totalWeight / 2;  // 平分后的每一份的重量
    // 初始化动态规划表,用于存储达到每一个重量所需的最小雨花石数量
    vector<vector<int>> dpTable(stoneCount + 1, vector<int>(halfWeight + 1, stoneCount));

    dpTable[0][0] = 0;

    // 动态规划过程
    for (int i = 1; i <= stoneCount; i++) {
        int currentWeight = stoneWeights[i - 1];
        for (int j = 0; j <= halfWeight; j++) {
            if (j < currentWeight) {
                dpTable[i][j] = dpTable[i - 1][j];
            } else {
                // 两种选择:不拿当前的雨花石或拿当前的雨花石
                int option1 = dpTable[i - 1][j];
                int option2 = dpTable[i - 1][j - currentWeight] + 1;
                // 选择需要雨花石数量较少的那一个
                dpTable[i][j] = min(option1, option2);
            }
        }
    }

    // 判断是否能够使用所有的雨花石达到halfWeight
    if (dpTable[stoneCount][halfWeight] == stoneCount) {
        return -1;
    }

    // 计算结果,选择拿或者不拿数量较小的那一边
    return min(stoneCount - dpTable[stoneCount][halfWeight], dpTable[stoneCount][halfWeight]);
}

int main() {
    int stoneCount;
    cin >> stoneCount;

    vector<int> stoneWeights(stoneCount);
    for (int i = 0; i < stoneCount; i++) {
        cin >> stoneWeights[i];
    }

    int result = checkSplit(stoneCount, stoneWeights);
    cout << result << endl;

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

codereasy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值