4

#yyds干货盘点# 动态规划专题:装箱问题

 1 year ago
source link: https://blog.51cto.com/u_15488507/5884297
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

#yyds干货盘点# 动态规划专题:装箱问题

精选 原创

97的风 2022-11-24 17:17:38 博主文章分类:面试题 ©著作权

文章标签 i++ 数据 java 文章分类 Java 编程语言 阅读数209

1.简述:

描述

有一个箱子容量为 V ,同时有n个物品,每个物品有一个体积(正整数)。每个物品只能使用一次。

要求n个物品中,任取若干个装入箱内,使箱子的剩余空间为最小。

数据范围: #yyds干货盘点# 动态规划专题:装箱问题_数据 , #yyds干货盘点# 动态规划专题:装箱问题_数据_02 ,每个物品的体积满足 #yyds干货盘点# 动态规划专题:装箱问题_i++_03

输入描述:

第一行输入一个正整数 V 表示箱子的容量,

第二行输入一个正整数 n 表示物品的个数。

后续 n 行每行输入一个正整数表示物品的体积    

输出描述:

输出箱子最小剩余空间

示例1

24
6
8
3
12
7
9
7

2.代码实现:

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int V=in.nextInt();
int n=in.nextInt();
int[] nums=new int[n];
for(int i=0;i<n;i++) nums[i]=in.nextInt();
boolean[] dp=new boolean[V+1];
dp[0]=true;
for(int i=0;i<n;i++){
for(int j=V;j>=nums[i];j--){
dp[j]=dp[j]|dp[j-nums[i]];
}
}
for(int i=V;i>=0;i--){
if(dp[i]){
System.out.println(V-i);
return;
}
}
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK