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); //输出最优价值