Huawei 2021 Fall Recruitment 0902 Written Test-Question 3 Backpack Problem

The title describes that
you work in a furniture company and need to send furniture to all parts of the country. For this, you need to load the boxes on trucks. The size and value of each box are different. You need to use the space of each truck as much as possible. Suppose the truck space size is K, given an array W, its i-th element represents the size of the i-th box, and given an array V, its i-th element represents the value of the i-th box, for this, How would you choose the boxes to be loaded on the truck to maximize the total value of the boxes transported by the truck on the premise that the space occupied by the truck is maximized?

Input description:
Parameter 1: Truck space K (1<K< 1000)
Parameter 2: Number of boxes N (1<N<1000)
Parameter 3: Each box size w (1<w<1000)
Parameter 4: Each Box value v (1<v<1000)

Output description:
On the premise of meeting the maximum space occupation of trucks, maximize the total value of boxes transported by trucks? Output the maximum total value of boxes transported by trucks.
Example 1
Input
9
5
2 2 4 6 3
3 4 8 9 6
Output
18

When I saw this problem, I thought it was a backpack problem and directly uploaded the code, but only 81% of it passed. I hope the netizens can analyze it and find the reason.

import java.util.Scanner;

public class Third {
    
    

    /**
     *
     * @param w  每个箱子尺寸w
     * @param v  每个箱子价值v
     * @param K  卡车空间K
     * @return
     */
    public static int knapSack(int[] w, int[] v, int K) {
    
    
        int size = w.length;
        if (size == 0) {
    
    
            return 0;
        }

        int[][] dp = new int[size][K + 1];
        //初始化第一行
        //仅考虑容量为K的背包放第0个物品的情况
        for (int i = 0; i <= K; i++) {
    
    
            dp[0][i] = w[0] <= i ? v[0] : 0;
        }
        //填充其他行和列
        for (int i = 1; i < size; i++) {
    
    
            for (int j = 0; j <= K; j++) {
    
    
                dp[i][j] = dp[i - 1][j];
                if (w[i] <= j) {
    
    
                    dp[i][j] = Math.max(dp[i][j], v[i] + dp[i - 1][j - w[i]]);
                }
            }
        }
        return dp[size - 1][K];
    }

    public static void main(String[] args) {
    
    
        Scanner sc = new Scanner(System.in);
        int K = sc.nextInt();//卡车空间
        int N = sc.nextInt();//箱子个数
        int[] w = new int[N];//每个箱子的尺寸
        int[] v = new int[N];//每个箱子的价值
        for (int i = 0; i < w.length; i++) {
    
    
            w[i] = sc.nextInt();
        }
        for (int i = 0; i < v.length; i++) {
    
    
            v[i] = sc.nextInt();
        }
        System.out.println(knapSack(w, v, K));
    }
}

Note: This code only passes 81% of the use cases.

Guess you like

Origin blog.csdn.net/weixin_43419256/article/details/108374997