using System; class Item { public int value, weight; public Item(int v, int w) { value = v; weight = w; } } class Program { static double FractionalKnapsack(Item[] items, int capacity) { Array.Sort(items, (a, b) => (b.value / (double)b.weight).CompareTo(a.value / (double)a.weight)); double totalValue = 0.0; int remaining = capacity; foreach (var item in items) { if (item.weight <= remaining) { totalValue += item.value; remaining -= item.weight; } else { totalValue += item.value * (remaining / (double)item.weight); break; } } return totalValue; } static void Main() { Item[] items = { new Item(60, 10), new Item(100, 20), new Item(120, 30) }; int capacity = 50; Console.WriteLine(FractionalKnapsack(items, capacity)); } }
The items are sorted by value/weight ratio: (60/10=6), (100/20=5), (120/30=4). We take all of the first two items (10+20=30 weight, 60+100=160 value), then 20 weight from the last item (20/30 fraction), adding 120*(20/30)=80 value. Total = 160+80=240.
Fractional knapsack allows breaking items into smaller parts to fill the knapsack optimally, unlike 0/1 knapsack where items are taken whole.
using System; class Item { public int value, weight; public Item(int v, int w) { value = v; weight = w; } } class Program { static double FractionalKnapsack(Item[] items, int capacity) { Array.Sort(items, (a, b) => (a.value / a.weight).CompareTo(b.value / b.weight)); double totalValue = 0.0; int remaining = capacity; foreach (var item in items) { if (item.weight <= remaining) { totalValue += item.value; remaining -= item.weight; } else { totalValue += item.value * (remaining / (double)item.weight); break; } } return totalValue; } static void Main() { Item[] items = { new Item(60, 10), new Item(100, 20), new Item(120, 30) }; int capacity = 50; Console.WriteLine(FractionalKnapsack(items, capacity)); } }
The sorting compares integer division (value/weight) which truncates decimals, causing incorrect order and thus incorrect total value.
Ratios: 40/2=20, 100/20=5, 50/10=5. Take full (40,2), then 13 weight from (100,20) (65%), total weight 15.
Fractional knapsack is a continuous problem allowing partial items, so greedy picking by ratio is optimal. 0/1 knapsack is discrete, requiring dynamic programming.
