题解 | #【模板】完全背包#

【模板】完全背包

https://www.nowcoder.com/practice/237ae40ea1e84d8980c1d5666d1c53bc

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static int solution(int V, int[][] wuping) {
        int[] dp = new int[V + 1];
        for (int i = 1; i <= V; i++) {
            for (int j = 0; j < wuping.length; j++) {
                int[] item = wuping[j];
                if (i >= item[0]) {
                    dp[i] = Math.max(dp[i], dp[i - item[0]] + item[1]);
                }
            }
        }
        return dp[V];
    }

    public static int solution2(int V, int[][] wuping) {
        int[] dp = new int[V + 1];
        Arrays.fill(dp, -1);
        dp[0] = 0;
        for (int i = 1; i <= V; i++) {
            for (int j = 0; j < wuping.length; j++) {
                int[] item = wuping[j];
                if (i >= item[0] && dp[i - item[0]] >= 0) {
                    dp[i] = Math.max(dp[i], dp[i - item[0]] + item[1]);
                }
            }
        }
        return dp[V] < 0 ? 0 : dp[V];
    }


    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int V = in.nextInt();
        int[][] wuping = new int[n][];
        for (int i = 0; i < wuping.length; i++) {
            int tiji = in.nextInt();
            int value = in.nextInt();
            wuping[i] = new int[] {tiji, value};
        }
        int res = solution(V, wuping);
        System.out.println(res);
        System.out.println(solution2(V, wuping));
    }
}

全部评论

相关推荐

11-18 15:57
门头沟学院 Java
最终归宿是测开:这个重邮的大佬在重邮很有名的,他就喜欢打92的脸,越有人质疑他,他越觉得爽😂
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务