55 lines
1.7 KiB
C#
55 lines
1.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using Google.OrTools.LinearSolver;
|
|
|
|
namespace knapsack
|
|
{
|
|
public class Program
|
|
{
|
|
private static Tuple<int, IEnumerable<Tuple<int, int>>> GetData(string filename)
|
|
{
|
|
var lines = File.ReadAllLines(filename);
|
|
var sizeWeight = lines[0];
|
|
var strings = sizeWeight.Replace(" ", " ").Split(' ');
|
|
var weight = int.Parse(strings[1]);
|
|
var items = lines.Skip(1).Select(line => line.Replace(" ", " ").Split(' ')).Select(split => new Tuple<int, int>(int.Parse(split[0]), int.Parse(split[1])));
|
|
return new Tuple<int, IEnumerable<Tuple<int, int>>>(weight, items);
|
|
}
|
|
|
|
static void Main(string[] args)
|
|
{
|
|
var data = GetData(args[0]);
|
|
var maxWeight = data.Item1;
|
|
var items = data.Item2;
|
|
|
|
var solver = Solver.CreateSolver("IntegerProgramming", "CBC_MIXED_INTEGER_PROGRAMMING");
|
|
solver.SetMaximization();
|
|
var weightConstraint = solver.MakeConstraint(double.NegativeInfinity, maxWeight, "weight");
|
|
|
|
var i = 0;
|
|
var variables = new List<Variable>();
|
|
foreach (var tuple in items)
|
|
{
|
|
var value = tuple.Item1;
|
|
var weight = tuple.Item2;
|
|
var var = solver.MakeIntVar(0.0, 1.0, "i" + i++);
|
|
variables.Add(var);
|
|
solver.SetObjectiveCoefficient(var, value);
|
|
weightConstraint.SetCoefficient(var, weight);
|
|
}
|
|
|
|
var resultStatus = solver.Solve();
|
|
|
|
// The objective value of the solution.
|
|
Console.WriteLine(solver.ObjectiveValue() + " 0");// + (resultStatus == Solver.OPTIMAL ? "1" : "0"));
|
|
|
|
// The value of each variable in the solution.
|
|
var takeItems = string.Join(" ", variables.Select(v => v.SolutionValue()).ToArray());
|
|
|
|
Console.WriteLine(takeItems);
|
|
}
|
|
}
|
|
}
|