Knapsack backtracking
#include<stdio.h>
void knapsack(int, int[], int[], int);
void backtrack(int, int, int[], int[], int, int*, int*, int[]);
int main()
{
int capacity, n;
printf("Enter the number of items: ");
scanf("%d", &n);
int weights[n], profits[n];
printf("Enter weights of the items: ");
for (int i = 0; i < n; i++) {
scanf("%d", &weights[i]);
}
printf("Enter profits of the items: ");
for (int i = 0; i < n; i++) {
scanf("%d", &profits[i]);
}
printf("Enter the capacity of the knapsack: ");
scanf("%d", &capacity);
knapsack(n, weights, profits, capacity);
return 0;
}
void knapsack(int n, int weights[], int profits[], int capacity)
{
int maxProfit = 0;
int currentWeight = 0, currentProfit = 0;
int included[n]; // Track items included in the knapsack
int bestSet[n]; // Track the best combination of items
for (int i = 0; i < n; i++) {
included[i] = 0;
bestSet[i] = 0;
}
backtrack(0, n, weights, profits, capacity, &maxProfit, ¤tWeight, included);
printf("Max profit is: %d\n", maxProfit);
printf("Items included in the knapsack: ");
for (int i = 0; i < n; i++) {
if (included[i]) {
printf("%d ", i + 1);
}
}
printf("\n");
}
void backtrack(int i, int n, int weights[], int profits[], int capacity, int *maxProfit, int *currentWeight, int included[])
{
if (i == n) { // Reached the end of items
int currentProfit = 0;
for (int j = 0; j < n; j++) {
if (included[j]) {
currentProfit += profits[j];
}
}
if (currentProfit > *maxProfit) {
*maxProfit = currentProfit;
}
return;
}
// Exclude the current item
backtrack(i + 1, n, weights, profits, capacity, maxProfit, currentWeight, included);
// Include the current item if it fits
if (*currentWeight + weights[i] <= capacity) {
included[i] = 1;
*currentWeight += weights[i];
backtrack(i + 1, n, weights, profits, capacity, maxProfit, currentWeight, included);
*currentWeight -= weights[i]; // Backtrack
included[i] = 0; // Reset the inclusion state
}
}
Comments
Post a Comment