/// <summary> /// 有了物品,有了方法,下面就是将两者结合起来的贪心算法GreedyAlgo /// </summary> /// <param name="problem"></param> /// <param name="greedyCallback"></param> public void CalculateResult(TagProblem problem, MethodDelegate greedyCallback) { int index = 0; int currSumWeight = 0; //先选 while ((index = greedyCallback(problem.objs, currSumWeight)) != -1) { if (problem.objs[index].Weight + currSumWeight <= problem.total) { ////如果背包没有装满,还可以再装,标记下装进去的物品状态为1 problem.objs[index].Status = 1; //把这个idx的物体的重量装进去,计算当前的重量 currSumWeight += problem.objs[index].Weight; Console.WriteLine("index:{0},price:{1},weight:{2}", index, problem.objs[index].Price, problem.objs[index].Weight); } else { //不能选这个物品了,做个标记2后重新选剩下的 problem.objs[index].Status = 2; } Console.WriteLine("currSumWeight:{0}", currSumWeight); } }
public PackageProblem() { tagObjects.Add(new TagObject() { Weight = 35, Price = 10, Status = 0 }); tagObjects.Add(new TagObject() { Weight = 30, Price = 40, Status = 0 }); tagObjects.Add(new TagObject() { Weight = 60, Price = 30, Status = 0 }); tagObjects.Add(new TagObject() { Weight = 50, Price = 50, Status = 0 }); tagObjects.Add(new TagObject() { Weight = 40, Price = 35, Status = 0 }); tagObjects.Add(new TagObject() { Weight = 10, Price = 40, Status = 0 }); tagObjects.Add(new TagObject() { Weight = 25, Price = 30, Status = 0 }); TagProblem problem = new TagProblem(); problem.objs = tagObjects; problem.total = 150; method = new MethodDelegate(CostToPriceWeight); CalculateResult(problem, method); Console.ReadLine(); }