Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- int max(int a, int b) {
- return (a > b) ? a : b;
- }
- int main() {
- int n, m;
- // Read the number of items
- printf("Enter the number of items: ");
- scanf("%d", &n);
- // Arrays to store profits and weights
- int P[n + 1], wt[n + 1];
- // Read the profits and weights
- printf("Enter the profits of the items:\n");
- for (int i = 1; i <= n; i++) {
- printf("Profit of item %d: ", i);
- scanf("%d", &P[i]);
- }
- printf("Enter the weights of the items:\n");
- for (int i = 1; i <= n; i++) {
- printf("Weight of item %d: ", i);
- scanf("%d", &wt[i]);
- }
- // Read the maximum weight capacity
- printf("Enter the maximum weight capacity of the knapsack: ");
- scanf("%d", &m);
- // DP table
- int K[n + 1][m + 1];
- for (int i = 0; i <= n; i++) {
- for (int w = 0; w <= m; w++) {
- if (i == 0 || w == 0) {
- K[i][w] = 0;
- } else if (wt[i] <= w) {
- K[i][w] = max(P[i] + K[i - 1][w - wt[i]], K[i - 1][w]);
- } else {
- K[i][w] = K[i - 1][w];
- }
- }
- }
- // Print the DP table
- printf("DP Table:\n");
- for (int i = 0; i <= n; i++) {
- for (int w = 0; w <= m; w++) {
- printf("%d\t", K[i][w]);
- }
- printf("\n");
- }
- printf("Maximum profit is %d\n", K[n][m]);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment