using Google.OrTools.Algorithms; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlabHandle { public class OR_T { public static IDictionary> Main(string[] args) { KnapsackSolver solver = new KnapsackSolver( KnapsackSolver.KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, "KnapsackExample"); long[] values = args[0].Replace("{", "").Replace("}", "").Split(new char[] { ',' }).ToList().ConvertAll(p => long.Parse(p)).ToArray(); long[] values2 = args[1].Replace("{", "").Replace("}", "").Split(new char[] { ',' }).ToList().ConvertAll(p => long.Parse(p)).ToArray(); long[,] weights = OneD_2(values2, 1); long[] capacities = args[2].Replace("{", "").Replace("}", "").Split(new char[] { ',' }).ToList().ConvertAll(p => long.Parse(p)).ToArray(); List result = new List(); long strResult = 0; Dictionary> dicResult = new Dictionary>(); solver.Init(values, weights, capacities); long computedValue = solver.Solve(); string selectItems = $"Selected item indexs : "; //strResult = computedValue.ToString(); for (int i = 0; i < values.Length; i++) { if (solver.BestSolutionContains(i)) { result.Add(values[i].ToString()); strResult += weights[0, i]; } } dicResult.Add(strResult.ToString(), result); return dicResult; } /// /// 一维数组转2维数组(矩阵) /// /// /// 矩阵行数 /// public static T[,] OneD_2(T[] obj, int len) { if (obj.Length % len != 0) return null; int width = obj.Length / len; T[,] obj2 = new T[len, width]; for (int i = 0; i < obj.Length; i++) { obj2[i / width, i % width] = obj[i]; } return obj2; } } }