【发布时间】:2019-02-12 22:56:54
【问题描述】:
我正在针对同一问题实施this question 中描述的方法,但我认为这不起作用。
对于那些不想在那里学习数学的人,这里是代数的要点:
Average = Sum(S1)/n(S1) = Sum(S2)/ n(S2) = Sum(Total)/n(Total)
where n() stands for the number of elements in the array & Sum() stands for the cumulative sum
S1 和 S2 是数组 Total 的互斥子集。因此,要找到满足此条件的所需子集,我们找到Sum(S1) = Sum(Total) * n(S1)/n(Total)
我的做法:
#include <bits/stdc++.h>
using namespace std;
bool SubsetSum(vector<int> &A, int Sum)
{
bool dp[Sum+1][A.size()+1];
int i, j;
for(i=0; i<= A.size(); i++)
dp[0][i] = false; // When sum = 0
for(i=0; i<=Sum; i++)
dp[i][0] = 1; // When num of elements = 0
for(i = 1; i <= A.size(); i++)
{
for(j=1; j<= Sum; j++)
{
dp[i][j] = dp[i-1][j];
if(j-A[i-1] >= 0)
dp[i][j] = dp[i][j] || dp[i-1][j-A[i-1]];
}
}
return dp[Sum][A.size()];
}
void avgset(vector<int> &A) {
int total = accumulate(A.begin(), A.end(), 0); // Cumulative sum of the vector A
int ntotal = A.size(); // Total number of elements
int i;
for(i=1; i<=ntotal; i++) // Subset size can be anything between 1 to the number of elements in the total subset
{
if((total * i) % ntotal == 0)
{
if(SubsetSum(A, (total * i)/ntotal)) // Required subset sum = total * i)/ntotal
cout<<"Array can be broken into 2 arrays each with equal average of "<<(total * i)/ntotal<<endl;
}
}
}
int main()
{
vector<int> A = {1, 7, 15, 29, 11, 9};
avgset(A);
return 0;
}
这段代码输出:
Array can be broken into 2 arrays each with equal average of 12
Array can be broken into 2 arrays each with equal average of 36
Array can be broken into 2 arrays each with equal average of 60
但这些答案是错误的。
例如,当子集总和 = 12 时,对应的元素将为{11, 1}。然后:
(11 + 1)/2 != (7 + 15 + 29 + 9)/4
我在这里误解了什么吗?
【问题讨论】:
标签: algorithm dynamic-programming knapsack-problem subset-sum