Skip to content

Commit 66ef03e

Browse files
New Commit
1 parent b633beb commit 66ef03e

File tree

3 files changed

+38
-11
lines changed

3 files changed

+38
-11
lines changed

01_Knapsack.c

Lines changed: 38 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,7 @@
22

33
int max(int a, int b) { return (a > b) ? a : b; }
44

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)
5+
int knapSack(int W, int wt[], int pt[], int n, int solutionVector[n])
86
{
97
int i, w;
108
int K[n + 1][W + 1];
@@ -15,28 +13,48 @@ int knapSack(int W, int wt[], int val[], int n)
1513
if (i == 0 || w == 0)
1614
K[i][w] = 0;
1715
else if (wt[i - 1] <= w)
18-
K[i][w] = max(val[i - 1]
19-
+ K[i - 1][w - wt[i - 1]],
16+
K[i][w] = max(pt[i - 1] + K[i - 1][w - wt[i - 1]],
2017
K[i - 1][w]);
2118
else
2219
K[i][w] = K[i - 1][w];
2320
}
2421
}
2522

23+
// To get the solution vector
24+
int count = 0, flag, base = K[n][W];
25+
26+
for(i=n;i>0;i--){
27+
int j = i-1;
28+
base = base - count;
29+
flag=0;
30+
// Checks if the weight is unique for the given value of i
31+
for(w = 0; w<=W; w++){
32+
if(K[j][w] == base){
33+
solutionVector[i-1] = 0;
34+
count = 0;
35+
flag = 1;
36+
break;
37+
}
38+
}
39+
if(flag == 1) // Not unique (determined from above)
40+
continue;
41+
else{
42+
solutionVector[i-1] = 1;
43+
count = pt[i-1];
44+
}
45+
}
46+
2647
return K[n][W];
2748
}
2849

2950
// Driver Code
3051
int main()
3152
{
32-
/*int profit[] = { 60, 100, 120 };
33-
int weight[] = { 10, 20, 30 };
34-
int W = 50;*/
3553
int i, n;
3654
printf("Enter number of items: ");
3755
scanf("%d", &n);
3856

39-
int profit[n], weight[n], W;
57+
int profit[n], weight[n], W, solutionVector[n];
4058
printf("Enter the profits and weights:\n");
4159
for(i=0;i<n;i++){
4260
printf("Item %d\n", i+1);
@@ -47,9 +65,18 @@ int main()
4765
printf("\n");
4866
}
4967

50-
printf("Enter the capacity of the Knapsack: ");
68+
printf("Profits and their weights:\n\n");
69+
for(i=0;i<n;i++){
70+
printf("p[%d] = %d\tw[%d] = %d\n", i, profit[i], i, weight[i]);
71+
}
72+
73+
printf("\nEnter the capacity of the Knapsack: ");
5174
scanf("%d", &W);
5275

53-
printf("Profit: %d", knapSack(W, weight, profit, n));
76+
int max_profit = knapSack(W, weight, profit, n, solutionVector);
77+
printf("Solution Vector: ");
78+
for(i = 0; i < n; i++) printf("%d ", solutionVector[i]);
79+
80+
printf("\nMaximum Profit: %d\n", max_profit);
5481
return 0;
5582
}

01_Knapsack.exe

512 Bytes
Binary file not shown.

job_scheduling.exe

0 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)