Reputation: 43
I'm currently trying data structures and algorithms through a combination of online resources. For one of them, I attempted to solve the famous knapsack problem via a greedy algorithm.
I'm sorting the weights and values of the problem in decreasing order before the loop in order to improve performance.
When I run the code, I get a bad_alloc. Does this mean I'm just not allocating the memory that I need to? I've been looking for a solution but nothing has really been helpful so far, as I'm not doing explicit access to memory with the "new" identifier.
Here's the code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool decreaseSort(int a, int b)
{
return a > b; //sort by decreasing value for better performance
}
double get_optimal_value(int capacity, vector<int> weights, vector<int> values) {
sort(weights.begin(),weights.end(), decreaseSort); //sort weights
sort(values.begin(),weights.end(), decreaseSort); //sort values
vector<int> ourKnapsack(values.size()); //set Knapsack to n elements
for (size_t i = 0; i < ourKnapsack.size(); i++)
ourKnapsack.push_back(0); //fill with zeroes
double totalValue = 0.0; //total worth
int ourInput = 0; //what we are putting in
for (size_t j = 0; j < ourKnapsack.size(); j++){
double unitValue = values.at(j)/weights.at(j); //ratio of value to weight for specific item
if (capacity == 0)
return totalValue; //end program, return value
if (weights.at(j) < capacity){
ourInput = weights.at(j); //if we have room, fill with the weight
}
else {
ourInput = capacity; //fill the rest of the pack
}
totalValue = totalValue * (ourInput * unitValue); //update totalValue
weights.at(j)-=ourInput; //subtract weight by what we put in
ourKnapsack.at(j)+=ourInput; //update knapsack element
capacity-=ourInput; //shrink capacity
}
return totalValue;
}
int main() {
int n = 3; //test case, 3 items, capacity of 50
int capacity = 50;
vector<int> values(n);
values = {60,100,120};
vector<int> weights(n);
weights = {20,50,30};
double optimal_value = get_optimal_value(capacity, weights, values);
std::cout.precision(10);
std::cout << optimal_value << std::endl; //should return optimal value
return 0;
}
Thanks in advance
Upvotes: 0
Views: 147
Reputation: 8576
for (size_t i = 0; i < ourKnapsack.size(); i++)
ourKnapsack.push_back(0); //fill with zeroes
This will go into an infinite loop.
Upvotes: 1