You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
92 lines
2.8 KiB
92 lines
2.8 KiB
/*
|
|
小红书最近决定举办一场盛大的红蓝PK!为了公平的分出红蓝两个阵营,每个人都获得了一个数字ai代表目己的战斗力,随后,由小红书“抽奖组件”这个程序来自动划分阵营,使得红方队员的总战斗力等于蓝方的总战斗力
|
|
然而,并不是每一局游戏都能找到这样完美的分配方案,已有的程序显然已经不够用了。让我们来新增一个总战斗力。前置程序吧,你只需要计算出每一局双方战斗力差值的最小绝对值。
|
|
*/
|
|
#include <iostream>
|
|
#include <vector>
|
|
#include <cmath>
|
|
#include <numeric>
|
|
using namespace std;
|
|
|
|
int findClosestSum(vector<int>& nums, int target) {
|
|
int sum = accumulate(nums.begin(), nums.end(), 0); // 数组元素的总和
|
|
int maxSum = min(sum, target + abs(sum - target)); // 限制最大的可能和
|
|
vector<bool> dp(maxSum + 1, false); // dp数组,初始为 false
|
|
dp[0] = true; // 和为 0 是可能的
|
|
// 动态规划填充 dp 数组
|
|
for (int num : nums) {
|
|
for (int i = maxSum; i >= num; --i) {
|
|
dp[i] = dp[i] || dp[i - num];
|
|
}
|
|
}
|
|
// 从 dp 数组中找到最接近目标值的和
|
|
int closest = 0;
|
|
for (int i = 0; i <= maxSum; ++i) {
|
|
if (dp[i] && abs(i - target) < abs(closest - target)) {
|
|
closest = i;
|
|
}
|
|
}
|
|
return closest;
|
|
}
|
|
|
|
int main() {
|
|
int n;
|
|
vector<int> arr;
|
|
int val, sum = 0;
|
|
cin >> n;
|
|
for(int i = 0; i < n; i++){
|
|
cin >> val;
|
|
sum += val;
|
|
arr.push_back(val);
|
|
}
|
|
int arv = sum / 2;
|
|
int tmp = findClosestSum(arr, arv);
|
|
cout << tmp << endl;
|
|
cout << arv - tmp + sum - tmp - arv << endl;
|
|
return 0;
|
|
}
|
|
|
|
|
|
#include <iostream>
|
|
#include <vector>
|
|
#include <cmath>
|
|
#include <numeric>
|
|
|
|
using namespace std;
|
|
|
|
int findClosestSum(vector<int>& nums, int target) {
|
|
int n = nums.size();
|
|
int sum = accumulate(nums.begin(), nums.end(), 0); // 数组元素的总和
|
|
|
|
int maxSum = min(sum, target + abs(sum - target)); // 限制最大的可能和
|
|
vector<bool> dp(maxSum + 1, false); // dp数组,初始为 false
|
|
dp[0] = true; // 和为 0 是可能的
|
|
|
|
// 动态规划填充 dp 数组
|
|
for (int num : nums) {
|
|
for (int i = maxSum; i >= num; --i) {
|
|
dp[i] = dp[i] || dp[i - num];
|
|
}
|
|
}
|
|
|
|
// 从 dp 数组中找到最接近目标值的和
|
|
int closest = 0;
|
|
for (int i = 0; i <= maxSum; ++i) {
|
|
if (dp[i] && abs(i - target) < abs(closest - target)) {
|
|
closest = i;
|
|
}
|
|
}
|
|
|
|
return closest;
|
|
}
|
|
|
|
int main() {
|
|
vector<int> nums = {7,3,5,3}; // 输入数组
|
|
int target = 10; // 目标值
|
|
|
|
int result = findClosestSum(nums, target);
|
|
|
|
cout << result << endl;
|
|
|
|
return 0;
|
|
}
|