最终重量在0-1背包?

时间:2014-05-24 20:08:37

标签: algorithm dynamic-programming knapsack-problem

如何找到0-1背包问题DP解决方案的最佳组合的最终重量?给定一组'n'个项目,每个项目都有自己的权重和价值。

#include <cstdio>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;

vector < pair <int, int> > arr;
map < pair <int, int>, int > hash_memo;
pair <int, int> temp;

int knapsack(int N, int budget)
{
    int a, b=0;
    pair <int, int> local;
    if((!N) || (!budget)) return 0;
    local.first = N;
    local.second = budget;
    if(hash_memo[local]) return hash_memo[local];

    a = knapsack(N-1, budget);
    if(budget >= arr[N-1].first)
    {
        b =  arr[N-1].second + knapsack(N-1, budget - arr[N-1].first);
    }

    if(a>b)
    {
        hash_memo[local] = a;
        return a; 
    }
    hash_memo[local] = b;
    return b;
}

int main()
{
int budget, N, a, b;

    while(1)
    {
        scanf("%d %d", &budget, &N);
        if((!budget) && (!N)) break;

        arr.clear();
        hash_memo.clear();
        for(int i=0; i<N; i++)
        {
            scanf("%d %d", &a, &b);
            if(b==0) continue;
            temp.first = a; temp.second = b;
            arr.push_back(temp);
        }

        int max_value = knapsack(N, budget);
        printf("%d\n", max_value);
    }

return 0;
}

以上是0-1背包问题的代码,其中'max_value'给出最优集的最终值。你如何找到'max_weight'? 'N'是项目数,'预算'是可以考虑的最大权重。

1 个答案:

答案 0 :(得分:0)

返回一对包含重量和值的值:

pair<int, int> knapsack(int N, int budget)
{
    if((!N) || (!budget)) return pair<int, int>(0, 0);

    pair<int, int> local(N, budget);
    if(hash_memo[local].second) return hash_memo[local];

    pair<int, int> b = pair<int, int>(0, 0);
    pair<int, int> a = knapsack(N-1, budget);
    if(budget >= arr[N-1].first)
    {
        pair<int, int> c = knapsack(N-1, budget - arr[N-1].first);
        b = pair<int, int>(c.first + arr[N-1].first, c.second + arr[N-1].second);
    }

    if(a.second > b.second)
    {
        return hash_memo[local] = a;
    }
    return hash_memo[local] = b;
}