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

01 Knapsack Program

The document presents a C program that implements the 0/1 Knapsack problem using dynamic programming. It allows users to input the number of objects, their weights, and profits, and calculates the maximum profit that can be obtained within a given knapsack capacity. The program also outputs the selected objects along with their weights and profits.

Uploaded by

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

01 Knapsack Program

The document presents a C program that implements the 0/1 Knapsack problem using dynamic programming. It allows users to input the number of objects, their weights, and profits, and calculates the maximum profit that can be obtained within a given knapsack capacity. The program also outputs the selected objects along with their weights and profits.

Uploaded by

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

Program: 0/1 Knapsack

#include <stdio.h>

int n, W, w[10], v[10], V[10][10], x[10];

int max(int a, int b)


{
if (a > b)
return a;
else
return b;
}

void knapsack()
{
int i, j;
for (i = 0; i <= n; i++)
{
for (j = 0; j <= W; j++)
{
if (i == 0 || j == 0)
V[i][j] = 0;
else if (j < w[i])
V[i][j] = V[i-1][j];
else
V[i][j] = max(V[i-1][j], v[i] + V[i-1][j-w[i]]);
printf("%d\t", V[i][j]);
}
printf("\n");
}
}

void printsolution()
{
int i = n, j = W;
while (i != 0 && j != 0)
{
if (V[i][j] != V[i-1][j])
{
x[i] = 1;
j = j - w[i];
}
else
{
x[i] = 0;
}
i--;
}
}

int main()
{
int i;
printf("Enter number of objects\n");
scanf("%d", &n);

printf("Enter knapsack capacity\n");


scanf("%d", &W);

printf("Enter the weights of the objects\n");


for (i = 1; i <= n; i++)
scanf("%d", &w[i]);

printf("Enter profits of the objects\n");


for (i = 1; i <= n; i++)
scanf("%d", &v[i]);

knapsack();
printsolution();

printf("Object\tWeight\tProfit\n");
for (i = 1; i <= n; i++)
{
if (x[i] == 1)
printf("%d\t%d\t%d\n", i, w[i], v[i]);
}

printf("Maximum profit is %d\n", V[n][W]);

return 0;
}

You might also like