Created
February 21, 2014 16:32
-
-
Save nsmaciej/9137556 to your computer and use it in GitHub Desktop.
Borken knapsack (input in input.txt below)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
5 3 | |
1 6 | |
2 10 | |
3 12 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdbool.h> | |
#define each(_a, _b) for (_a = 0; _a < _b; ++_a) | |
#define max(_a, _b) ((_a) > (_b) ? (_a) : (_b)) | |
#define unless(_a) if (!(_a)) | |
int knapsack(int c, int n, int W[], int V[]) { | |
int i, j; | |
int K[c+1][n+1]; | |
each (j, n+1) { | |
each (i, c+2) { | |
if (i == 0 || j == 0) { | |
K[i][j] = 0; | |
} else if (W[j] <= c) { | |
K[i][j] = max(V[j-1] + K[c-W[j-1]][j-1], K[c][j-1]); | |
} else { | |
K[i][j] = K[i][j - 1]; | |
} | |
} | |
} | |
puts("K ="); | |
each (j, n+1) { | |
each (i, c+1) { | |
printf("%d ", K[i][j]); | |
} | |
printf("\n"); | |
} | |
return K[c][n]; | |
} | |
int main(void) { | |
int c, n, i; | |
int *V, *W; | |
scanf("%d %d", &c, &n); | |
V = calloc(n, sizeof(int)); | |
W = calloc(n, sizeof(int)); | |
each(i, n) | |
scanf("%d %d", &W[i], &V[i]); | |
printf("%d\n", knapsack(c, n, W, V)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment