UVA 624 01背包求方案

题目:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=565


题意:给定背包容量,给定物品个数,然后是物品,价值和体积相等。求最大价值时的放入方案,多解输出一解即可


思路:每次更新背包时顺便记录被谁跟新的即可,然后逆向求方案,正向输出


总结:背包和DP忘得差不多了。。。忧伤。。。是时候刷一波了

#include 
#include 
#include 
#include 
using namespace std;

const int N = 10010;
int dp[30][N], jl[30][N];
int val[N], res[N];

int main()
{
    int n, m;
    while(~ scanf("%d", &n))
    {
        scanf("%d", &m);
        for(int i = 0; i < m; i++)
            scanf("%d", val + i);

        memset(dp, 0, sizeof dp);
        for(int i = 0; i < m; i++)
            for(int j = 0; j <= n; j++)
                if(j < val[i]) dp[i+1][j] = dp[i][j], jl[i+1][j] = -1;
                else
                {
                    if(dp[i][j] < dp[i][j-val[i]] + val[i])
                        dp[i+1][j] = dp[i][j-val[i]] + val[i], jl[i+1][j] = i; /*更新背包时记录由谁更新*/
                    else dp[i+1][j] = dp[i][j], jl[i+1][j] = -1;
                }
        
        int tmp = n, k = 0;
        for(int i = m; i >= 1; i--)
            if(jl[i][tmp] != -1)
                res[k++] = val[jl[i][tmp]], tmp = tmp - val[i-1];
        
        for(int i = k - 1; i >= 0; i--)
            printf("%d ", res[i]);
        printf("sum:%d\n", dp[m][n]);
    }
    return 0;
}



你可能感兴趣的:(乱搞dp)