using System;
using System.Collections.Generic;
using System.Linq;
class Item {
public int value;
public int weight;
public double ratio;
public Item(int value, int weight)
{
this.value = value;
this.weight = weight;
this.ratio = (double)value / weight;
}
}
class KnapsackNode {
public List<int> items;
public int value;
public int weight;
public KnapsackNode(List<int> items, int value,
int weight)
{
this.items = items;
this.value = value;
this.weight = weight;
}
}
class Knapsack {
public int maxWeight;
public List<Item> items;
public Knapsack(int maxWeight, List<Item> items)
{
this.maxWeight = maxWeight;
this.items = items;
}
public int Solve()
{
items = items.OrderByDescending(i = > i.ratio)
.ToList();
int bestValue = 0;
Queue<KnapsackNode> q = new Queue<KnapsackNode>();
q.Enqueue(new KnapsackNode(new List<int>(), 0, 0));
while (q.Count > 0) {
KnapsackNode node = q.Dequeue();
int i = node.items.Count;
if (i == items.Count) {
bestValue = Math.Max(bestValue, node.value);
}
else {
Item item = items[i];
KnapsackNode withItem = new KnapsackNode(
new List<int>(node.items),
node.value + item.value,
node.weight + item.weight);
if (IsPromising(withItem, maxWeight,
bestValue)) {
q.Enqueue(withItem);
}
KnapsackNode withoutItem = new KnapsackNode(
new List<int>(node.items), node.value,
node.weight);
if (IsPromising(withoutItem, maxWeight,
bestValue)) {
q.Enqueue(withoutItem);
}
}
}
return bestValue;
}
private bool IsPromising(KnapsackNode node,
int maxWeight, int bestValue)
{
return node.weight <= maxWeight
&& node.value + GetBound(node) > bestValue;
}
private int GetBound(KnapsackNode node)
{
int remainingWeight = maxWeight - node.weight;
int bound = node.value;
for (int i = node.items.Count; i < items.Count;
i++) {
Item item = items[i];
if (remainingWeight >= item.weight) {
bound += item.value;
remainingWeight -= item.weight;
}
else {
bound
+= (int)(remainingWeight * item.ratio);
break;
}
}
return bound;
}
}