0% found this document useful (0 votes)
2 views2 pages

Knapsack Problem

The document presents a C program that implements the Knapsack problem using dynamic programming. It prompts the user to input the number of items, the maximum capacity of the knapsack, and the weights and profits of the items. The program calculates and displays the optimal solution for the given inputs.

Uploaded by

deadshotlev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Knapsack Problem

The document presents a C program that implements the Knapsack problem using dynamic programming. It prompts the user to input the number of items, the maximum capacity of the knapsack, and the weights and profits of the items. The program calculates and displays the optimal solution for the given inputs.

Uploaded by

deadshotlev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

KNAPSACK PROBLEM

#include <stdio.h>
int n, W, i, j, p[10], w[10], M[10][10];
int knapsack()
{
int i, j;
for (i = 0; i <= n; i++)
{
for (j = 0; j <= W; j++)
{
if (i == 0 || j == 0)
M[i][j] = 0;
else if (w[i] > j)
M[i][j] = M[i - 1][j];
else
M[i][j] = (M[i - 1][j] > M[i - 1][j - w[i]] + p[i]) ? M[i - 1][j] :
M[i - 1][j - w[i]] + p[i];
printf("%d\t", M[i][j]);
}
printf("\n");
}
printf("Optimal solution: %d\n", M[n][W]);
return M[n][W];
}
int main()
{
printf("Enter the number of items: ");
scanf("%d", &n);
printf("Enter the max capacity of the knapsack: ");
scanf("%d", &W);
printf("Enter the weight of each object:\n");
for (i = 1; i <= n; i++)
scanf("%d", &w[i]);
printf("Enter the profit of each object:\n");
for (i = 1; i <= n; i++)
scanf("%d", &p[i]);
int optimal_solution = knapsack();
return 0;
}

OUTPUT:

Enter the number of items: 5


Enter the max capacity of the knapsack: 6
Enter the weight of each object:
3
2
1
4
5
Enter the profit of each object:
25
20
15
40
50
0 0 0 0 0 0 0
0 0 0 25 25 25 25
0 0 20 25 25 45 45
0 15 20 35 40 45 60
0 15 20 35 40 55 60
0 15 20 35 40 55 65
Optimal solution: 65

You might also like