0-1背包问题是一个经典的组合优化问题,其问题描述如下:
有一个容量为 C C C 的背包,和 n n n 个物品,每个物品有重量 w i w_i wi 和价值 v i v_i vi,现在需要从这 n n n 个物品中选择一些物品放入背包中,使得这些物品的总重量不超过 C C C,且这些物品的总价值最大。
0-1背包问题是一个 NP 完全问题,因此不存在多项式时间复杂度的算法能够求解该问题。但是,我们可以使用多种算法来求解该问题,包括动态规划、贪心、回溯、分支定界算法等。
动态规划算法是求解0-1背包问题的一种常用算法,其时间复杂度较低,能够求解较大规模的问题。动态规划算法的基本思想是将原问题分解为若干个子问题,先求解子问题,再由子问题的解得到原问题的解。
动态规划算法求解0-1背包问题的时间复杂度为 O ( n ∗ c ) O(n*c) O(n∗c),空间复杂度为 O ( n ∗ c ) O(n*c) O(n∗c),其中 n n n 表示物品的数量, c c c 表示背包的容量。
/**
* 动态规划求解0-1背包问题
* @param w 物品重量
* @param v 物品价值
* @param c 背包容量
* @return 背包能装下的最大价值
* 时间复杂度:O(n*c)
* 空间复杂度:O(n*c)
* 优点:时间复杂度较低,能够求解较大规模的问题
* 缺点:空间复杂度较高,不适用于数据量较大的问题
*/
public static int knapsack(int[] w, int[] v, int c) {
int n = w.length;
int[][] dp = new int[n + 1][c + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= c; j++) {
if (j < w[i - 1]) {
// 背包容量不足,不能装入第i个物品
dp[i][j] = dp[i - 1][j];
} else {
// 能装入第i个物品
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - w[i - 1]] + v[i - 1]);
}
}
}
// 返回背包能装下的最大价值
return dp[n][c];
}
贪心算法是求解0-1背包问题的一种常用算法,其时间复杂度较低,能够求解较大规模的问题。贪心算法的基本思想是每次选择当前最优的解,直到得到最终的解。
贪心算法求解0-1背包问题的时间复杂度为 O ( n ∗ l o g ( n ) ) O(n*log(n)) O(n∗log(n)),空间复杂度为 O ( n ) O(n) O(n)。
/**
* 贪心算法求解0-1背包问题
* @param w 物品重量
* @param v 物品价值
* @param c 背包容量
* @return 背包能装下的最大价值
* 时间复杂度:O(n*log(n))
* 空间复杂度:O(n)
* 优点:时间复杂度较低,能够求解较大规模的问题
* 缺点:不能保证求得的是最优解,只能得到一个近似解
*/
public static int greedyKnapsack(int[] w, int[] v, int c) {
int n = w.length;
int[] index = new int[n];
for (int i = 0; i < n; i++) {
index[i] = i;
}
int[] temp = new int[n];
for (int i = 0; i < n; i++) {
temp[i] = v[i] * w[i];
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (temp[i] < temp[j]) {
int t = temp[i];
temp[i] = temp[j];
temp[j] = t;
t = index[i];
index[i] = index[j];
index[j] = t;
}
}
}
int maxValue = 0;
for (int i = 0; i < n; i++) {
if (w[index[i]] <= c) {
maxValue += v[index[i]];
c -= w[index[i]];
} else {
maxValue += (int) ((double) v[index[i]] / w[index[i]] * c);
break;
}
}
return maxValue;
}
回溯算法是求解0-1背包问题的一种常用算法,其能够求解较小规模的问题。回溯算法的基本思想是搜索所有可能的解,找到最优解。
回溯算法求解0-1背包问题的时间复杂度为 O ( 2 n ) O(2^n) O(2n),空间复杂度为 O ( n ) O(n) O(n)。
/**
* 回溯算法求解0-1背包问题
* @param w 物品重量
* @param v 物品价值
* @param c 背包容量
* @return 背包能装下的最大价值
* 时间复杂度:O(2^n)
* 空间复杂度:O(n)
* 优点:能够求解较小规模的问题
* 缺点:时间复杂度较高,不适用于数据量较大的问题
*/
public static int backtrackKnapsack(int[] w, int[] v, int c) {
int n = w.length;
int maxValue = 0;
for (int i = 0; i < (1 << n); i++) {
int currentWeight = 0;
int currentValue = 0;
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) != 0) {
currentWeight += w[j];
currentValue += v[j];
}
}
if (currentWeight <= c && currentValue > maxValue) {
maxValue = currentValue;
}
}
return maxValue;
}
分支定界算法是求解0-1背包问题的一种常用算法,其能够求解较小规模的问题。分支定界算法的基本思想是搜索所有可能的解,但是在搜索过程中,通过一些限制条件,剪枝掉一些不可能成为最优解的分支,从而减少搜索的时间。
分支定界算法求解0-1背包问题的时间复杂度为 O ( 2 n ) O(2^n) O(2n),空间复杂度为 O ( n ) O(n) O(n)。
/**
* 分支定界算法求解0-1背包问题
* @param w 物品重量
* @param v 物品价值
* @param c 背包容量
* @return 背包能装下的最大价值
* 时间复杂度:O(2^n)
* 空间复杂度:O(n)
* 优点:能够求解较小规模的问题
* 缺点:时间复杂度较高,不适用于数据量较大的问题
*/
public static int branchBoundKnapsack(int[] w, int[] v, int c) {
int n = w.length;
int[] index = new int[n];
for (int i = 0; i < n; i++) {
index[i] = i;
}
int[] temp = new int[n];
for (int i = 0; i < n; i++) {
temp[i] = v[i] * w[i];
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (temp[i] < temp[j]) {
int t = temp[i];
temp[i] = temp[j];
temp[j] = t;
t = index[i];
index[i] = index[j];
index[j] = t;
}
}
}
int maxValue = 0;
int currentValue = 0;
int currentWeight = 0;
int i = 0;
while (i >= 0) {
if (i == n) {
if (currentValue > maxValue) {
maxValue = currentValue;
}
i--;
} else if (currentWeight + w[index[i]] <= c) {
currentWeight += w[index[i]];
currentValue += v[index[i]];
i++;
} else {
i--;
}
if (i >= n || i < 0 || index[i] >= n || currentWeight + w[index[i]] > c || currentValue + (c - currentWeight) * (double) v[index[i]] / w[index[i]] <= maxValue) {
i--;
}
}
return maxValue;
}
/**
* 代码实现:
* 动态规划算法时间复杂度较低,能够求解较大规模的问题,但空间复杂度较高,不适用于数据量较大的问题。
* 贪心算法时间复杂度较低,能够求解较大规模的问题,但不能保证求得的解是最优解。
* 回溯算法能够求解较小规模的问题,但时间复杂度较高,不适用于数据量较大的问题。
* 分支定界算法能够求解较小规模的问题,但时间复杂度较高,不适用于数据量较大的问题。
*/
import java.util.Arrays;
public class KnapsackTest {
public static void main(String[] args) {
// 物品重量
int[] w = {2, 4, 6, 8, 9, 2, 4, 6, 8, 9, 2, 4, 6, 8, 9, 2, 4, 6, 8, 9};
// 物品价值
int[] v = {1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1, 3, 5, 7, 9};
// 背包容量1
int c1 = 10;
// 背包容量2
int c2 = 100;
long startTime1 = System.nanoTime();
int[] result1 = {knapsack(w, v, c1)};
long endTime1 = System.nanoTime();
long duration1 = (endTime1 - startTime1);
long startTime2 = System.nanoTime();
int[] result2 = {knapsack(w, v, c2)};
long endTime2 = System.nanoTime();
long duration2 = (endTime2 - startTime2);
System.out.println("当背包容量为10时,动态规划算法的结果为:" + result1[0] + ",执行时间为:" + duration1 + "纳秒");
System.out.println("当背包容量为10时,贪心算法的结果为:" + greedyKnapsack(w, v, c1) + ",执行时间为:" + (System.nanoTime() - endTime1) + "纳秒");
System.out.println("当背包容量为10时,回溯算法的结果为:" + backtrackKnapsack(w, v, c1) + ",执行时间为:" + (System.nanoTime() - endTime1) + "纳秒");
System.out.println("当背包容量为10时,分支定界算法的结果为:" + branchBoundKnapsack(w, v, c1) + ",执行时间为:" + (System.nanoTime() - endTime1) + "纳秒");
System.out.println("当背包容量为100时,动态规划算法的结果为:" + result2[0] + ",执行时间为:" + duration2 + "纳秒");
System.out.println("当背包容量为100时,贪心算法的结果为:" + greedyKnapsack(w, v, c2) + ",执行时间为:" + (System.nanoTime() - endTime2) + "纳秒");
System.out.println("当背包容量为100时,回溯算法的结果为:" + backtrackKnapsack(w, v, c2) + ",执行时间为:" + (System.nanoTime() - endTime2) + "纳秒");
System.out.println("当背包容量为100时,分支定界算法的结果为:" + branchBoundKnapsack(w, v, c2) + ",执行时间为:" + (System.nanoTime() - endTime2) + "纳秒");
}
/**
* 动态规划求解0-1背包问题
* @param w 物品重量
* @param v 物品价值
* @param c 背包容量
* @return 背包能装下的最大价值
* 时间复杂度:O(n*c)
* 空间复杂度:O(n*c)
* 优点:时间复杂度较低,能够求解较大规模的问题
* 缺点:空间复杂度较高,不适用于数据量较大的问题
*/
public static int knapsack(int[] w, int[] v, int c) {
int n = w.length;
int[][] dp = new int[n + 1][c + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= c; j++) {
if (j < w[i - 1]) {
// 背包容量不足,不能装入第i个物品
dp[i][j] = dp[i - 1][j];
} else {
// 能装入第i个物品
dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - w[i - 1]] + v[i - 1]);
}
}
}
// 返回背包能装下的最大价值
return dp[n][c];
}
/**
* 贪心算法求解0-1背包问题
* @param w 物品重量
* @param v 物品价值
* @param c 背包容量
* @return 背包能装下的最大价值
* 时间复杂度:O(n*log(n))
* 空间复杂度:O(n)
* 优点:时间复杂度较低,能够求解较大规模的问题
* 缺点:不能保证求得的是最优解,只能得到一个近似解
*/
public static int greedyKnapsack(int[] w, int[] v, int c) {
int n = w.length;
int[] index = new int[n];
for (int i = 0; i < n; i++) {
index[i] = i;
}
int[] temp = new int[n];
for (int i = 0; i < n; i++) {
temp[i] = v[i] * w[i];
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (temp[i] < temp[j]) {
int t = temp[i];
temp[i] = temp[j];
temp[j] = t;
t = index[i];
index[i] = index[j];
index[j] = t;
}
}
}
int maxValue = 0;
for (int i = 0; i < n; i++) {
if (w[index[i]] <= c) {
maxValue += v[index[i]];
c -= w[index[i]];
} else {
maxValue += (int) ((double) v[index[i]] / w[index[i]] * c);
break;
}
}
return maxValue;
}
/**
* 回溯算法求解0-1背包问题
* @param w 物品重量
* @param v 物品价值
* @param c 背包容量
* @return 背包能装下的最大价值
* 时间复杂度:O(2^n)
* 空间复杂度:O(n)
* 优点:能够求解较小规模的问题
* 缺点:时间复杂度较高,不适用于数据量较大的问题
*/
public static int backtrackKnapsack(int[] w, int[] v, int c) {
int n = w.length;
int maxValue = 0;
for (int i = 0; i < (1 << n); i++) {
int currentWeight = 0;
int currentValue = 0;
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) != 0) {
currentWeight += w[j];
currentValue += v[j];
}
}
if (currentWeight <= c && currentValue > maxValue) {
maxValue = currentValue;
}
}
return maxValue;
}
/**
* 分支定界算法求解0-1背包问题
* @param w 物品重量
* @param v 物品价值
* @param c 背包容量
* @return 背包能装下的最大价值
* 时间复杂度:O(2^n)
* 空间复杂度:O(n)
* 优点:能够求解较小规模的问题
* 缺点:时间复杂度较高,不适用于数据量较大的问题
*/
public static int branchBoundKnapsack(int[] w, int[] v, int c) {
int n = w.length;
int[] index = new int[n];
for (int i = 0; i < n; i++) {
index[i] = i;
}
int[] temp = new int[n];
for (int i = 0; i < n; i++) {
temp[i] = v[i] * w[i];
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (temp[i] < temp[j]) {
int t = temp[i];
temp[i] = temp[j];
temp[j] = t;
t = index[i];
index[i] = index[j];
index[j] = t;
}
}
}
int maxValue = 0;
int currentValue = 0;
int currentWeight = 0;
int i = 0;
while (i >= 0) {
if (i == n) {
if (currentValue > maxValue) {
maxValue = currentValue;
}
i--;
} else if (currentWeight + w[index[i]] <= c) {
currentWeight += w[index[i]];
currentValue += v[index[i]];
i++;
} else {
i--;
}
if (i >= n || i < 0 || index[i] >= n || currentWeight + w[index[i]] > c || currentValue + (c - currentWeight) * (double) v[index[i]] / w[index[i]] <= maxValue) {
i--;
}
}
return maxValue;
}
}
在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht
目录一.加解密算法数字签名对称加密DES(DataEncryptionStandard)3DES(TripleDES)AES(AdvancedEncryptionStandard)RSA加密法DSA(DigitalSignatureAlgorithm)ECC(EllipticCurvesCryptography)非对称加密签名与加密过程非对称加密的应用对称加密与非对称加密的结合二.数字证书图解一.加解密算法加密简单而言就是通过一种算法将明文信息转换成密文信息,信息的的接收方能够通过密钥对密文信息进行解密获得明文信息的过程。根据加解密的密钥是否相同,算法可以分为对称加密、非对称加密、对称加密和非
华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o
这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/
HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候