Program 7 Design and implement C Program to solve discrete Knapsack and continuous Knapsack problems using greedy approximation method.
Program 7 Design and implement C Program to solve discrete Knapsack and continuous Knapsack problems using greedy approximation method.
This program first calculates the profit-to-weight ratio for each item, then sorts the items based
on this ratio in non-increasing order. It then fills the knapsack greedily by selecting items with
the highest ratio until the knapsack is full. If there's space left in the knapsack after selecting
whole items, it adds fractional parts of the next item. Finally, it prints the optimal solution and
the solution vector.
Here's a simplified version of the C program to solve discrete Knapsack and continuous
Knapsack problems using the greedy approximation method:
#include <stdio.h>
#define MAX 50
temp2 = p[i];
p[i] = p[j];
p[j] = temp2;
}
}
}
int currentWeight = 0;
maxprofit = 0.0;
// Fill the knapsack with items
for (i = 0; i < n; i++) {
if (currentWeight + w[i] <= m) {
x[i] = 1; // Item i is selected
currentWeight += w[i];
maxprofit += p[i];
} else {
// Fractional part of item i is selected
x[i] = (m - currentWeight) / (double)w[i];
maxprofit += x[i] * p[i];
break;
}
}
int main() {
printf("Enter the number of objects: ");
scanf("%d", &n);
greedyKnapsack(n, w, p, m);
return 0;
}