标题:背包问题或者动态规划求解
只看楼主
半世烟尘
Rank: 1
等 级:新手上路
帖 子:5
专家分:4
注 册:2015-3-23
结帖率:0
已结贴  问题点数:10 回复次数:2 
背包问题或者动态规划求解
Consider the partition problem: given a set S of n positive integers, partition it into two disjoint subsets S1 and S2 such that the discrepancy

                            E(S) = |sum(S1) - sum(S2)|

is minimized, where sum(Si) is the sum of Si's elements. Design an exhaustive search algorithm for this problem.
就是求2组数各自和的最小差的绝对值
搜索更多相关主题的帖子: elements positive positive positive problem elements elements search problem Design search problem search Design Design 
2016-01-02 17:40
azzbcc
Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19Rank: 19
来 自:江西财经大学
等 级:贵宾
威 望:81
帖 子:3293
专家分:12919
注 册:2012-11-4
得分:10 
程序代码:
/*

 * 将问题转换为求容量为sum/2的背包问题

 * 物体的重量为其具体值

 */

#include <stdio.h>

#define N sizeof(s) / sizeof(s[0])

int s[] = { 2, 5, 3, 1, 6, 4, 6, 7, 3, 4 };

int getSum()
{
    int sum = 0;

    for (int i = 0;i < N;i++)
    {
        sum += s[i];
    }
    return sum;
}

int fun(int n)
{
    int f[N + 1][n + 1];

    for (int i = 0;i <= N;i++)
    {
        for (int j = 0;j <= n;j++)
        {
            if (i == 0 || j == 0)
            {
                f[i][j] = 0;
                printf("%3d", f[i][j]);
                continue;
            }
            f[i][j] = f[i - 1][j];
            if (s[i - 1] <= j && f[i - 1][j - s[i - 1]] + s[i - 1] > f[i][j])
            {
                f[i][j] = f[i - 1][j - s[i - 1]] + s[i - 1];
            }
            printf("%3d", f[i][j]);
        }
        printf("\n");
    }

    return f[N][n];
}

int main(void)
{
    int sum = getSum();
    int max = fun(sum / 2);

    printf("max = %d\n", max);
    printf("ans = %d\n", sum - 2 * max);
    return 0;
}


[fly]存在即是合理[/fly]
2016-01-02 20:39
半世烟尘
Rank: 1
等 级:新手上路
帖 子:5
专家分:4
注 册:2015-3-23
得分:0 
回复 2楼 azzbcc
噢噢,好的,谢谢,我一会试试。
2016-01-02 20:48



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-460764-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.019531 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved