
代码如下:
#include<stdio.h>
int knapsack(int weight[], int value[], int count[], int n, int capacity)
{
int* dp = (int*)malloc(sizeof(int) * (capacity + 1));
for (int i = 0; i <= capacity; i++)
{
dp[i] = 0;
}
for (int i = 0; i < n; i++)//核心代码
{
for (int j = capacity; j >= weight[i]; j--)
{
for (int k = 0; k <= count[i] && k * weight[i] <= j; k++)
{
if (dp[j] < dp[j - k * weight[i]] + value[i] * k)
{
dp[j] = dp[j - weight[i] * k] + k * value[i];
}
}
}
}
int result = dp[capacity];
free(dp);
return result;
}
int main()
{
int weight[] = { 1,2,3 };//物品重量
int value[] = { 3,2,1 };//物品价值
int count[] = { 2,2,2 };//物品数量
int n = sizeof(weight) / sizeof(weight[0]);//物品种类
int capacity = 9;//背包容量
int valuemax = knapsack(weight, value, count, n, capacity);
printf("背包能装下的最大价值为: %d\n", valuemax);
return 0;
}