#include <iostream>
#include <cstdio>
using namespace std;
const int W = 3;
const int N = 3;
void printKnapsackTable (int K[][W+1]) {
printf("\nKnapsack Table\n");
for (int i=0; i<=N; i++) {
for (int j=0; j<=W; j++) {
printf("%d ", K[i][j]);
}
printf("\n");
}
}
void findKnapsackItems(int K[][W+1], int wt[], int val[]) {
int i=N, res=K[N][W], w=W;
printf("\nKnapsack Items:\n");
while (i>0 && res>0) {
if (res != K[i-1][w]) {
printf("%d - %d is selected\n", i, val[i-1]);
res = res - val[i-1];
w = w - wt[i-1];
}
i=i-1;
}
}
int knapsack (int wt[], int val[], int K[][W+1]) {
// Building table K[][] in bottom manner
for(int i=0; i<=N; i++) {
for(int w=0; w <= W; w++) {
// Base case: empty knapsack
if (i == 0 || w == 0) {
K[i][w] = 0;
} else if (wt[i-1] <= w) {
// Selecting val[i-1] if it gives higher
// knapsack value
K[i][w] = max((val[i-1] + K[i-1][w-wt[i-1]]),
K[i-1][w]);
} else {
// Not including val[i-1]:
// if wt[i-1] is greater than
// available knapsack capacity
K[i][w] = K[i-1][w];
}
}
}
return K[N][W];
}
int main() {
// your code goes here
int val[] = {60, 100, 120};
int wt[] = {1, 2, 1};
int K[N+1][W+1] = {0};
printf("Knapsack Value: %d", knapsack(wt, val, K));
printKnapsackTable(K);
findKnapsackItems(K, wt, val);
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y3N0ZGlvPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwpjb25zdCBpbnQgVyA9IDM7CmNvbnN0IGludCBOID0gMzsKCnZvaWQgcHJpbnRLbmFwc2Fja1RhYmxlIChpbnQgS1tdW1crMV0pIHsKCXByaW50ZigiXG5LbmFwc2FjayBUYWJsZVxuIik7Cglmb3IgKGludCBpPTA7IGk8PU47IGkrKykgewoJCWZvciAoaW50IGo9MDsgajw9VzsgaisrKSB7CgkJCXByaW50ZigiJWQgIiwgS1tpXVtqXSk7CgkJfQoJCXByaW50ZigiXG4iKTsKC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