Algorithm 0-1背包的最终重量?

Algorithm 0-1背包的最终重量?,algorithm,dynamic-programming,knapsack-problem,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 >

如何找到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;
}
#包括
#包括
#包括
#包括
使用名称空间std;
向量arr;
maphash\u memo;
对温;
整数背包(整数N,整数预算)
{
int a,b=0;
配对本地;
如果((!N)|(!预算))返回0;
local.first=N;
本地。第二=预算;
if(hash_memo[local])返回hash_memo[local];
a=背包(N-1,预算);
如果(预算>=arr[N-1]。第一个)
{
b=arr[N-1]。第二个+背包(N-1,预算-arr[N-1]。第一个);
}
如果(a>b)
{
hash_memo[本地]=a;
返回a;
}
hash_memo[本地]=b;
返回b;
}
int main()
{
国际预算,N,a,b;
而(1)
{
scanf(“%d%d”、&budget、&N);
如果(!预算)和(!N))中断;
arr.clear();
hash_memo.clear();

对于(int i=0;i返回一对包含权重和值的值:

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;
}
成对背包(整数N,整数预算)
{
if((!N)|(!budget))返回对(0,0);
对本地(N,预算);
if(hash_memo[local].second)返回hash_memo[local];
对b=对(0,0);
a对=背包(N-1,预算);
如果(预算>=arr[N-1]。第一个)
{
对c=背包(N-1,预算-arr[N-1]。第一);
b=对(c.first+arr[N-1]。第一,c.second+arr[N-1]。第二);
}
如果(a秒>b秒)
{
返回hash_memo[本地]=a;
}
返回hash_memo[本地]=b;
}

在这个答案中,我学到了一些非常新的东西。对我的代码片段进行了非常简洁的修改。非常感谢。非常有帮助:)