C#應用靜態計劃處理0-1背包成績實例剖析。本站提示廣大學習愛好者:(C#應用靜態計劃處理0-1背包成績實例剖析)文章只能為提供參考,不一定能成為您想要的結果。以下是C#應用靜態計劃處理0-1背包成績實例剖析正文
本文實例講述了C#應用靜態計劃處理0-1背包成績的辦法。分享給年夜家供年夜家參考。詳細以下:
// 應用靜態計劃處理0-1背包成績
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Knapsack_problem
// 背包成績症結在於盤算不跨越背包的總容量的最年夜價值
{
class Program
{
static void Main()
{
int i;
int capacity = 16;
int[] size = new int[] { 3, 4, 7, 8, 9 };
// 5件物品每件年夜小分離為3, 4, 7, 8, 9
//且是弗成朋分的 0-1 背包成績
int[] values = new int[] { 4, 5, 10, 11, 13 };
// 5件物品每件的價值分離為4, 5, 10, 11, 13
int[] totval = new int[capacity + 1];
// 數組totval用來存貯最年夜的總價值
int[] best = new int[capacity + 1];
// best 存貯的是以後價值最高的物品
int n = values.Length;
for (int j = 0; j <= n - 1; j++)
for (i = 0; i <= capacity; i++)
if (i >= size[j])
if (totval[i] < (totval[i - size[j]] + values[j]))
// 假如以後的容量減去J的容量再加上J的價值比本來的價值年夜,
//就將這個值傳給以後的值
{
totval[i] = totval[i - size[j]] + values[j];
best[i] = j; // 並把j傳給best
}
Console.WriteLine("背包的最年夜價值: " + totval[capacity]);
// Console.WriteLine("組成背包的最年夜價值的物品是: " );
// int totcap = 0;
// while (totcap <= capacity)
// {
// Console.WriteLine("物品的年夜小是:" + size[best[capacity - totcap]]);
// for (i = 0; i <= n-1; i++)
// totcap += size[best[i]];
// }
}
}
}
願望本文所述對年夜家的C#法式設計有所贊助。