0% found this document useful (0 votes)
7 views

Daa

Uploaded by

nishantbasak1234
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)
7 views

Daa

Uploaded by

nishantbasak1234
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

WRITE A C PROGRAM ON BINARY KNAPSACK PROBLEM:

#include <stdio.h>
int max(int a, int b)
{
return (a > b) ? a : b;
}
(int n, int W, int weights[], int values[])
{
int dp[n + 1][W + 1];
for (int i = 0; i <= n; i++) {
for (int w = 0; w <= W; w++) {
dp[i][w] = 0;
}
}
for (int i = 1; i <= n; i++)
{
for (int w = 0; w <= W; w++)
{
if (weights[i - 1] <= w)
{
dp[i][w] = max(dp[i - 1][w], dp[i - 1][w - weights[i - 1]] + values[i - 1]);
}
else
{
dp[i][w] = dp[i - 1][w];
}
}
}
printf("Maximum value in Knapsack = %d\n",
dp[n][W]);
}
int main()
{
int n;
int W;
printf("Enter the number of items: ");
scanf("%d", &n);
printf("Enter the capacity of the knapsack: ");
scanf("%d", &W);
int weights[n];
int values[n];
printf("Enter weights of the items:\n");
for (int i = 0; i < n; i++) {
printf("Weight of item %d: ", i + 1);
scanf("%d", &weights[i]);
}
printf("Enter values of the items:\n");
for (int i = 0; i < n; i++)
{
printf("Value of item %d: ", i + 1);
scanf("%d", &values[i]);
}
knapsack(n, W, weights, values);
return 0;
}

You might also like