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

【模板】完全背包

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));
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
去B座二楼砸水泥地:不过也可以理解,这种应该没参加过秋招
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务