Files
hello-algo/ja/codes/csharp/chapter_greedy/fractional_knapsack.cs
Yudong Jin 7257641e0e Retranslate the complete Japanese online edition from Chinese (#2008)
* Retranslate the complete Japanese online edition from Chinese

* Fit Japanese homepage labels and localize heading permalinks

* Point Japanese contribution instructions to the Japanese preview

* Replace locale conditionals with multilingual UI tables
2026-10-30 02:12:26 +08:00

52 lines
1.8 KiB
C#

/**
* File: fractional_knapsack.cs
* Created Time: 2023-07-21
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_greedy;
/* 品物 */
class Item(int w, int v) {
public int w = w; // 品物の重さ
public int v = v; // 品物の価値
}
public class fractional_knapsack {
/* 分割可能ナップサック問題:貪欲法 */
double FractionalKnapsack(int[] wgt, int[] val, int cap) {
// 重さと価値の 2 つの属性を持つ品物のリストを作成する
Item[] items = new Item[wgt.Length];
for (int i = 0; i < wgt.Length; i++) {
items[i] = new Item(wgt[i], val[i]);
}
// 単位重さ当たりの価値 item.v / item.w の降順にソートする
Array.Sort(items, (x, y) => (y.v / y.w).CompareTo(x.v / x.w));
// 貪欲な選択を繰り返す
double res = 0;
foreach (Item item in items) {
if (item.w <= cap) {
// 残り容量が十分なら、現在の品物を丸ごとナップサックに入れる
res += item.v;
cap -= item.w;
} else {
// 残り容量が不足している場合、現在の品物の一部をナップサックに入れる
res += (double)item.v / item.w * cap;
// 残り容量がないため、ループを終了する
break;
}
}
return res;
}
[Test]
public void Test() {
int[] wgt = [10, 20, 30, 40, 50];
int[] val = [50, 120, 150, 210, 240];
int cap = 50;
// 貪欲アルゴリズム
double res = FractionalKnapsack(wgt, val, cap);
Console.WriteLine("ナップサックの容量を超えない品物の最大価値は " + res);
}
}