Loading

AcWing 12. 背包问题求具体方案

题目链接

https://www.acwing.com/problem/content/12/

题解

f[i][j]:表示从i-n中选,总体积不超过j的最大价值
这种"向前"的状态转移方式,是一种可以考虑的状态刻画方式

AC代码

/*
f[i][j]:表示从i-n中选,总体积不超过j的最大价值
*/
import java.util.*;

public class Main {
    static int N = 1010;
    static int[][] f = new int[N][N];
    static int[] v = new int[N], w = new int[N];
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(), m = sc.nextInt();
        for (int i = 1; i <= n; i ++) {
            v[i] = sc.nextInt();
            w[i] = sc.nextInt();
        }
        for (int i = n; i >= 1; i --)
            for (int j = 0; j <= m; j ++) {
                f[i][j] = f[i + 1][j];
                if (j >= v[i]) f[i][j] = Math.max(f[i][j], f[i + 1][j - v[i]] + w[i]);
            }
        
        List<Integer> res = new ArrayList<>();
        for (int i = 1, t = m; i <= n; i ++) {
            // 注意选取之后需要减去已经选的体积
            if (t - v[i] >= 0 && f[i][t] == f[i + 1][t - v[i]] + w[i]) {
                res.add(i);
                t -= v[i];
            }
        }
        for (Integer ele : res) {
            System.out.print(ele + " ");
        }
    }
}
posted @ 2022-04-06 21:43  Doubest  阅读(18)  评论(0编辑  收藏  举报