#include #include void init_things(int n, int weight[n], int profit[n]) { int i = 0; for (i = 0; i < n; i++) { weight[i] = i; profit[i] = n-i; } } void print_things(int n, int weight[n], int profit[n]) { int i = 0; printf("Weights\n"); for (i = 0; i < n; i++) { printf("%2d ", weight[i]); } printf("\n"); printf("Profits\n"); for (i = 0; i < n; i++) { printf("%2d ", profit[i]); } printf("\n"); } int print_table(int n, int c, int total[n][c], int use[n][c]) { int i, j; printf("Total Profit\n"); for (j = 0; j < c; j++) { for (i = 0; i < n; i++) { printf("%2d ",total[i][j]); } printf("\n"); } printf("Flags\n"); for (j = 0; j < c; j++) { for (i = 0; i < n; i++) { printf("%2d ",use[i][j]); } printf("\n"); } } int solver(int n, int c, int weight[n], int profit[n], int total[n][c], int use[n][c]) { int i, j; /* Max profit using thing 0, if it fits */ for (j = 0; j < c; j++) { if (weight[0] > j) { total[0][j] = 0; use[0][j] = 0; } else { total[0][j] = profit[0]; use[0][j] = 1; } } for (i = 1; i < n; i++) { for (j = 0; j < c; j++) { if ( (j= total[i-1][j-weight[i]] + profit[i])) { total[i][j] = total[i-1][j]; use[i][j] = 0; } else { total[i][j] = total[i-1][j-weight[i]] + profit[i]; use[i][j] = 1; } } } } int main(int argc, char *argv[]) { int i, n, c; int *weights, *profits; int (*table)[c], (*flags)[c]; if (argc <= 2) { fprintf(stdout, "usage %s n c\n", argv[0]); exit(1); } n = atoi(argv[1]); /* Number of things */ c = atoi(argv[2]); /* Capacity of knapsack */ if ((n < 0) || (c < 0)) { fprintf(stdout, "usage %s n c - where n and c >= 0\n", argv[0]); exit(1); } weights = malloc(sizeof(int [n])); profits = malloc(sizeof(int [n])); init_things(n, weights, profits); print_things(n, weights, profits); table = malloc(sizeof (int [n][c])); flags = malloc(sizeof (int [n][c])); solver(n, c, weights, profits, table, flags); print_table(n,c,table,flags); }