01背包怎么知道拿了哪个物品
程序代码:
#include <stdio.h> #include <stdlib.h> #include <malloc.h> int main(void) { unsigned max_value(unsigned*, unsigned*, size_t, unsigned); unsigned num, capacity, maxvalue; printf("输入物品个数:"); scanf_s("%u", &num, 1); printf("输入背包容量:"); scanf_s("%u", &capacity); printf("\n"); unsigned *value = (unsigned *)malloc(sizeof(unsigned) * num + 1); unsigned *weight = (unsigned *)malloc(sizeof(unsigned) * num + 1); value[0] = 0; weight[0] = 0; for (size_t i = 1; i <= num; i++) { printf("输入第%d个物品需要的容量和价值:", i); scanf_s("%u%u", &weight[i], &value[i], 2); } maxvalue = max_value(value, weight, num, capacity); printf("%u\n", maxvalue); system("pause"); return 0; } unsigned max_value(unsigned *value, unsigned *need, size_t num, unsigned capacity) { unsigned *x = (unsigned *)malloc(sizeof(unsigned) * (capacity + 1)); unsigned maxvalue; size_t i, j; for (j = 0; j <= capacity; j++) x[j] = 0; for (i = 1; i <= num; i++) { for (j = capacity; j; j--) if (j >= need[i] && value[i] + x[j - need[i]] > x[j]) x[j] = value[i] + x[j - need[i]]; for (j = 0; j <= capacity; j++) printf("%6u\t", x[j]); printf("\n\n"); } maxvalue = x[capacity]; free(x); return maxvalue; }
[此贴子已经被作者于2019-1-17 11:02编辑过]