Java Algorithm_AcWing3: Complete Knapsack Problem

acwing3 - complete knapsack problem

There are N items and a knapsack of capacity V, and infinite pieces of each item are available.

The volume of the i-th item is v_i, and the value is w_i.

Solving which items to put into the backpack can make the total volume of these items not exceed the capacity of the backpack, and the total value is the largest.
output the maximum value.

input format

In the first line, two integers, N and V, are separated by spaces, which represent the number of items and the volume of the backpack respectively.

Then there are N lines, and each line has two integers v_i, w_i, separated by spaces, representing the volume and value of the i-th item respectively.

output format

Output an integer representing the maximum value.

data range

0<N,V≤10000<N,V≤1000
0<vi,wi≤10000<vi,wi≤1000

input style

4 5
1 2
2 4
3 4
4 5

output sample

10

Analysis diagram:

image-20221228180503266

AC

package AcWing.acwing3_完全背包问题;

import java.util.Scanner;

public class Main {
    
    
    int num = 1010;
    int N, V;
    int[] n = new int[num];
    int[] v = new int[num];
    int[] dp = new int[num];

    public static void main(String[] args) {
    
    
        new Main().process();
    }

    void process() {
    
    
        Scanner scanner = new Scanner(System.in);
        N = scanner.nextInt();
        V = scanner.nextInt();

        for (int i = 1; i <= N; i++) {
    
    
            n[i] = scanner.nextInt();
            v[i] = scanner.nextInt();
        }
        
/*
        for (int i = 1; i <= N; i++)
            for (int j = 0; j <= V; j++)
                for (int k = 0; k * n[i] <= j; k++)
                    dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - k * n[i]] + k * v[i]);
          System.out.println(dp[N][V]);
*/

        for (int i = 1; i <= N; i++) {
    
    
            for (int j = n[i]; j <= V; j++) {
    
        //注意了,这里的j是从小到大枚举
                dp[j] = Math.max(dp[j], dp[j - n[i]] + v[i]);
            }
        }

        System.out.println(dp[V]);
    }

}

image-20221227191004040

Guess you like

Origin blog.csdn.net/m0_59598325/article/details/128472263