【发布时间】:2022-01-09 03:28:12
【问题描述】:
我正在尝试使用蛮力递归解决方案解决 0/1 背包问题的代码,但是当我将问题的大小(利润和权重数组)设为 100 时,它会一直运行而没有任何输出。如果有的话能告诉我为什么吗?以及如何解决。
如果有人能告诉我什么时候可以找到可信的伪代码和 0/1 背包问题的代码。
#include <iostream>
#include <ctime>
#include <cmath>
using namespace std;
//Return the maximum value that can be put in a knapsack of capacity W
int knapsackRecursive(int profits[], int profitsLength, int weights[], int capacity, int currentIndex) {
// Base Case
if (capacity <= 0 || currentIndex >= profitsLength || currentIndex < 0)
return 0;
//If weight of the nth item is more than knapsack capacity W, then
// this item cannot be included in the optimal solgurion
int profit1 = 0;
if (weights[currentIndex] <= capacity)
profit1 = profits[currentIndex] + knapsackRecursive(profits, profitsLength, weights, capacity - weights[currentIndex], currentIndex + 1);
int profit2 = knapsackRecursive(profits, profitsLength, weights, capacity, currentIndex + 1);
//Return the maximum of two cases:
//(1) nth item included
//(2) not included
return max(profit1, profit2);
}
int knapSack(int profits[], int profitsLength, int weights[], int capacity) {
return knapsackRecursive(profits, profitsLength, weights, capacity, 0);
}
int main() {
int profits[100];
int weights[100];
int capacity = 300;
srand(time(0));
clock_t startTime;
clock_t endTime;
clock_t timeTaken = 0;
for (int i = 0; i < 20; i++) { //repeat the knapSack 20 times
for (int j = 0; j < 100; j++) {
profits[j] = 1 + (rand() % 100);
weights[j] = 1 + (rand() % 100);
}
startTime = clock();
knapSack(profits, 100, weights, capacity);
endTime = clock();
timeTaken = timeTaken + (endTime - startTime); //compute the total cpu time
}
cout << "The avearage of the time taken is" << ((float)timeTaken / CLOCKS_PER_SEC) / 20 << " seconds";
return 0;
}
【问题讨论】:
-
“行不通”是什么意思?它怎么行不通?请花一些时间阅读the help pages,阅读SO tour,阅读How to Ask,以及this question checklist。最后请学习如何edit您的问题以改进它们。
标签: c++ recursion knapsack-problem brute-force