Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,29 @@

using std::vector;

// finding the maximum index i.e the index for which values/weights is maximum
int get_max_index(vector<int> weights, vector<int> values) {
int max_i = 0;
double max = 0;

for (int i = 0; i < weights.size(); i++) {
if (weights[i] != 0 && (double) values[i] / weights[i] > max) {
max = (double) values[i] / weights[i];
max_i = i;
max_i = i; //maximum index
}
}
return max_i;
}

// filling the knapsack staring from the maximum index
double get_optimal_value(int capacity, vector<int> weights, vector<int> values) {
double value = 0.0;

for (int i = 0; i < weights.size(); i++) {
if (capacity == 0) return value;
if (capacity == 0) return value; // capacity of the knapsack
int index = get_max_index(weights, values);
int a = std::min(capacity, weights[index]);
value += a * (double) values[index] / weights[index];
int a = std::min(capacity, weights[index]);
value += a * (double) values[index] / weights[index]; // total value of item placed in knapsack
weights[index] -= a;
capacity -= a;
}
Expand All @@ -43,7 +45,7 @@ int main() {

double optimal_value = get_optimal_value(capacity, weights, values);

std::cout.precision(10);
std::cout.precision(10); //print the answer upto five decimal for error corrections
std::cout << optimal_value << std::endl;
return 0;
}