knapsack 0/1 program in c
knapsack 0/1 program in c
Fractional knapsack
#include <stdio.h>
#include <stdlib.h>
// Structure to store item details
typedef struct {
float value;
float weight;
float ratio;
} Item;
// Comparison function for sorting items by valueto-weight ratio
int compare(const void *a, const void *b) {
float r1 = ((Item *)a)->ratio;
float r2 = ((Item *)b)->ratio;
return (r1 < r2) ? 1 : (r1 > r2) ? -1 : 0;
}
// Function to solve the fractional knapsack problem
float fractionalKnapsack(Item items[], int n, float capacity) {
qsort(items, n, sizeof(Item), compare);
float totalValue = 0.0;
float remainingCapacity = capacity;
for (int i = 0; i < n; i++) {
if (items[i].weight <= remainingCapacity) {
totalValue += items[i].value;
remainingCapacity -= items[i].weight;
} else {
totalValue += items[i].ratio * remainingCapacity;
break;
}
}
return totalValue;
}
int main() {
int n;
float capacity;
printf("Enter the number of items: ");
scanf("%d", &n);
Item items[n];
printf("Enter the value and weight of each item:\n");
for (int i = 0; i < n; i++) {
scanf("%f %f", &items[i].value, &items[i].weight);
items[i].ratio = items[i].value / items[i].weight;
}
printf("Enter the capacity of the knapsack: ");
scanf("%f", &capacity);
float maxValue = fractionalKnapsack(items, n, capacity);
printf("Maximum value in knapsack = %.2f\n", maxValue);
return 0;
}
Output:
#include <stdio.h>
if (wt[n - 1] > W)
return knapSack(W, wt, val, n - 1);
else
return max(
val[n - 1]
+ knapSack(W - wt[n - 1], wt, val, n - 1),
knapSack(W, wt, val, n - 1));
}
int main()
{
int profit[] = { 60, 100, 120 };
int weight[] = { 10, 20, 30 };
int W = 50;
int n = sizeof(profit) / sizeof(profit[0]);
printf("%d", knapSack(W, weight, profit, n));
return 0;
}
Output: