#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX_N 100
#define MAX_C 100

// 定义结构体以存储背包问题的相关数据
typedef struct {
    int N; // 物体的个数
    int C; // 背包的容量
    int weight[MAX_N]; // 每个物体的重量
    int value[MAX_N]; // 每个物体的价值
    int DP[MAX_N][MAX_C]; // 动态规划表
} Bag;

void bag01NoRec(Bag* bag) {
    // 初始化 DP 表
    for (int j = 0; j <= bag->C; j++) {
        bag->DP[0][j] = 0;
    }

    // 填充 DP 表
    for (int i = 1; i <= bag->N; i++) {
        for (int j = 0; j <= bag->C; j++) {
            if (j >= bag->weight[i]) { // 如果容量为 j 的背包能够放下第 i 个物体
                bag->DP[i][j] = (bag->DP[i - 1][j - bag->weight[i]] + bag->value[i] > bag->DP[i - 1][j]) ?
                               (bag->DP[i - 1][j - bag->weight[i]] + bag->value[i]) : bag->DP[i - 1][j];
            } else {
                // 物体放不下，仅选择不放该物体
                bag->DP[i][j] = bag->DP[i - 1][j];
            }
        }
    }

    // 打印 DP 表
    for (int i = 0; i <= bag->N; i++) {
        for (int j = 0; j <= bag->C; j++) {
            printf("%d  ", bag->DP[i][j]);
        }
        printf("\n");
    }
}

void printResult(Bag* bag, int n, int v) {
    bool isAdd[MAX_N] = {false};
    for (int i = n; i >= 1; i--) {
        if (bag->DP[i][v] == bag->DP[i - 1][v])
            isAdd[i] = false;
        else {
            isAdd[i] = true;
            v -= bag->weight[i];
        }
    }
    for (int i = 1; i <= n; i++) {
        printf("%d号 %s; ", i, isAdd[i] ? "放" : "不放");
    }
    printf("\n");
}

// 使用 init2 函数初始化，并测试背包算法
void init2(Bag* bag) {
    bag->C = 6;
    bag->weight[1] = 3;
    bag->weight[2] = 2;
    bag->weight[3] = 6;
    bag->weight[4] = 5;
    bag->weight[5] = 4;
    bag->value[1] = 30;
    bag->value[2] = 60;
    bag->value[3] = 50;
    bag->value[4] = 40;
    bag->value[5] = 60;
    bag->N = 5;

    bag01NoRec(bag);
    printResult(bag, bag->N, bag->C);
}

int main() {
    Bag bag;
    init2(&bag);
    return 0;
}
