【问题标题】:C++ partition algorithmC++ 分区算法
【发布时间】:2018-09-18 15:39:03
【问题描述】:

我的任务是:

您有 N 个重量分别为 s1、s2...sN 的物品。程序必须将项目分成两组,以便项目重量尽可能相似。

我找到了一个很好的解释如何解决这个问题(作者: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 &lt;bits/stdc++.h&gt; - Don't do this.。包括正确的头文件。
  • 此代码取自网站,我已修复
  • 因此您只需要跟踪完整的递归路径以及运行总数即可。如果operator&lt; 仍然只比较运行总数,但您仍然返回整个获胜路径对象,您可以将整数总和替换为值类型来执行此操作(每个级别只需要 1 位来跟踪您采用的分支)。
  • 请注意,上述算法非常慢,运行时间为 O(2^n)。更好的方法是只运行一个二进制背包算法,目标总和是总和的一半。

标签: c++ partition knapsack-problem


【解决方案1】:

你需要这样的东西吗:

#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 2011-12-29
    相关资源
    最近更新 更多