const int M = 12;//背包重M斤
int[,] Subjects = {{3,4},{4,5},{5,7},{8,10} };//物件数组,重量/价值
int CurrentWeight = 0, CurrentValue = 0;//当前重量,当前价值
int MaxValue = 0;//最优价值
for (int i = 0; i < Subjects.GetUpperBound(0)+1; i++)
{
CurrentWeight = 0; CurrentValue = 0;
int j = i;//背包下标
while (CurrentWeight < M)
{
CurrentWeight += Subjects[j, 0];
CurrentValue += Subjects[j, 1];
if (CurrentWeight == M)
{
if (CurrentValue > MaxValue)//找到一个新的最大价值解。
{
MaxValue = CurrentValue;
CurrentValue -= Subjects[j, 1];
CurrentWeight -= Subjects[j, 0];
}
}
else if (CurrentWeight > M)
{
CurrentValue -= Subjects[j, 1];
CurrentWeight -= Subjects[j, 0];
}
if (j +1< Subjects.GetUpperBound(0)+1) j++; //开始取下一个值;
else break;
}
}
Console.Write(MaxValue); //输出最优价值
本文介绍了一个简单的0-1背包问题的解决方法,通过迭代选择不同物品以达到背包容量限制下的最大价值。使用C#实现算法流程,展示了如何通过循环结构找到最优解。
1739

被折叠的 条评论
为什么被折叠?



