C++分区算法
C++ partition algorithm
我的任务是:
您有 N 个项目,其重量为 s1、s2...锡。程序必须将项目分为两组,以便项目重量尽可能相似。
我找到了一个很好的解释如何解决这个问题(作者:Abhiraj Smit(:
// A Recursive C program to solve minimum sum partition
// problem.
#include <stdio.h>
using namespace std;
// Function to find the minimum sum
int findMinRec(int arr[], int i, int sumCalculated, int sumTotal)
{
// If we have reached last element. Sum of one
// subset is sumCalculated, sum of other subset is
// sumTotal-sumCalculated. Return absolute difference
// of two sums.
if (i==0)
return abs((sumTotal-sumCalculated) - sumCalculated);
// For every item arr[i], we have two choices
// (1) We do not include it first set
// (2) We include it in first set
// We return minimum of two choices
return min(findMinRec(arr, i-1, sumCalculated+arr[i-1], sumTotal),
findMinRec(arr, i-1, sumCalculated, sumTotal));
}
// Returns minimum possible difference between sums
// of two subsets
int findMin(int arr[], int n)
{
// Compute total sum of elements
int sumTotal = 0;
for (int i=0; i<n; i++)
sumTotal += arr[i];
// Compute result using recursive function
return findMinRec(arr, n, 0, sumTotal);
}
// Driver program to test above function
int main()
{
int arr[] = {3, 1, 4, 2, 2, 1};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "The minimum difference between two sets is "
<< findMin(arr, n);
return 0;
}
但问题是我还需要在屏幕上打印这两组数字,而在此代码上我只会得到最小的差异。
我真的很感激你的帮助,谢谢!
你需要这样的东西吗:
#include<iostream>
#include<math.h>
using namespace std;
int lim, ans = 0, k, min1 = INT_MAX;
int a[] = { 3, 1, 4, 2, 2, 1 };
int n = sizeof(a) / sizeof(a[0]);
int bit;
int main()
{
lim = 1 << n;
for (int i = 1; i < lim; i++)
{
k = 0;
for (int j = 1; j < (1 << n); (j = j << 1))
{
if (i&j)
ans += a[k];
else ans -= a[k];
k++;
}
k = 0;
if (min1 > abs(ans)) {
min1 = abs(ans);
bit = i;
}
ans = 0;
}
cout << min1 << endl;
cout << bit << endl;
int temp = 1;
for (int i = 0; i < n; i++) {
if (bit&temp) cout << a[i] << " ";
temp = temp << 1;
}
cout << endl;
temp = 1;
for (int i = 0; i < n; i++) {
if (!(bit&temp)) cout << a[i] << " ";
temp = temp << 1;
}
return 0;
}
相关文章:
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 基于ELO的团队匹配算法
- C++选择排序算法中的逻辑错误
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- C++A*算法并不总是在路径中具有目标节点
- 排序算法c++
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 算法问题:查找从堆栈中弹出的所有序列
- 下面是排序算法O(n)吗
- Coursera DSA 算法工具箱第 4 周第 2 个问题 - 分区纪念品
- 对多个(可能)重叠范围进行分区的最简单算法
- 迭代快速排序方法的分区算法问题
- C++分区算法
- 是否存在用于按以下方式对两个范围进行排序和分区的标准算法?
- 为什么我的递归快速排序算法有如此不平衡的分区
- 使用霍尔分区方案的快速排序算法返回原始未排序列表
- 标准库分区算法
- 矢量元素在分区算法中不交换
- 回文分区的这种算法的时间复杂度是多少?