Open swethareddy18 opened 1 year ago
Enter the capacity of knapsack: 50 Enter the number of items: 3 Enter the weight and value of 3 item: Weight[0]: 10 Value[0]: 60 Weight[1]: 20 Value[1]: 100 Weight[2]: 30 Value[2]: 120 Added object 1 (60 Rs., 10Kg) completely in the bag. Space left: 40. Added object 2 (100 Rs., 20Kg) completely in the bag. Space left: 20. Added 66% (120 Rs., 30Kg) of object 3 in the bag. Filled the bag with objects worth 240.00 Rs.
include
void main() { int capacity, no_items, cur_weight, item; int used[10]; float total_profit; int i; int weight[10]; int value[10];
printf("Enter the capacity of knapsack:\n"); scanf("%d", &capacity);
printf("Enter the number of items:\n"); scanf("%d", &no_items);
printf("Enter the weight and value of %d item:\n", no_items); for (i = 0; i < no_items; i++) { printf("Weight[%d]:\t", i); scanf("%d", &weight[i]); printf("Value[%d]:\t", i); scanf("%d", &value[i]); }
for (i = 0; i < no_items; ++i) used[i] = 0;
cur_weight = capacity; while (cur_weight > 0) { item = -1; for (i = 0; i < no_items; ++i) if ((used[i] == 0) && ((item == -1) || ((float) value[i] / weight[i] > (float) value[item] / weight[item]))) item = i;
}
printf("Filled the bag with objects worth %.2f Rs.\n", total_profit);