Skip to content

Commit d6a5559

Browse files
New Commit
1 parent fd683c0 commit d6a5559

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

0/1_Knapsack.c

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include<stdio.h>
2+
3+
int max(int a, int b) { return (a > b) ? a : b; }
4+
5+
// Returns the maximum value that
6+
// can be put in a knapsack of capacity W
7+
int knapSack(int W, int wt[], int val[], int n)
8+
{
9+
int i, w;
10+
int K[n + 1][W + 1];
11+
12+
// Build table K[][] in bottom up manner
13+
for (i = 0; i <= n; i++) {
14+
for (w = 0; w <= W; w++) {
15+
if (i == 0 || w == 0)
16+
K[i][w] = 0;
17+
else if (wt[i - 1] <= w)
18+
K[i][w] = max(val[i - 1]
19+
+ K[i - 1][w - wt[i - 1]],
20+
K[i - 1][w]);
21+
else
22+
K[i][w] = K[i - 1][w];
23+
}
24+
}
25+
26+
return K[n][W];
27+
}
28+
29+
// Driver Code
30+
int main()
31+
{
32+
/*int profit[] = { 60, 100, 120 };
33+
int weight[] = { 10, 20, 30 };
34+
int W = 50;*/
35+
int i, n;
36+
printf("Enter number of items: ");
37+
scanf("%d", &n);
38+
39+
int profit[n], weight[n], W;
40+
printf("Enter the profits and weights:\n");
41+
for(i=0;i<n;i++){
42+
printf("Item %d\n", i+1);
43+
printf("Profit: ");
44+
scanf("%d", &profit[i]);
45+
printf("Weight: ");
46+
scanf("%d", &weight[i]);
47+
printf("\n");
48+
}
49+
50+
printf("Enter the capacity of the Knapsack: ");
51+
scanf("%d", &W);
52+
53+
printf("Profit: %d", knapSack(W, weight, profit, n));
54+
return 0;
55+
}

0/1_Knapsack.exe

41.6 KB
Binary file not shown.

0 commit comments

Comments
 (0)