SolutionNode.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System.Collections.Generic;
  2. using System.Text;
  3. namespace TravMerchant
  4. {
  5. public class SolutionNode
  6. {
  7. public ReducableMatrix Matrix;
  8. public int? Value;
  9. public SolutionNode Parent;
  10. public SolutionNode Left;
  11. public SolutionNode Right;
  12. public SolutionNode(ReducableMatrix matrix)
  13. {
  14. Matrix = matrix;
  15. Parent = null;
  16. Value = matrix.CalculateLowerBound(0);
  17. }
  18. private SolutionNode(ReducableMatrix matrix, SolutionNode parent, int? lastSum, bool recalculate)
  19. {
  20. Matrix = matrix;
  21. Parent = parent;
  22. if (recalculate)
  23. {
  24. Value = matrix.CalculateLowerBound(lastSum);
  25. }
  26. else
  27. {
  28. matrix.CalculateLowerBound(lastSum);
  29. Value = lastSum;
  30. }
  31. }
  32. public bool HasChildren() => Left != null;
  33. public List<(int, int)> Solve()
  34. {
  35. var leaf = MinimalLeaf();
  36. for (; !leaf.IsSolved(); leaf = MinimalLeaf())
  37. {
  38. leaf.Calculate();
  39. }
  40. return leaf.Matrix.GetPath();
  41. }
  42. private SolutionNode MinimalLeaf()
  43. {
  44. if (HasChildren())
  45. {
  46. var leftMin = Left.MinimalLeaf();
  47. var rightMin = Right.MinimalLeaf();
  48. return leftMin.Value > rightMin.Value ? rightMin : leftMin;
  49. }
  50. return this;
  51. }
  52. public void Calculate()
  53. {
  54. int?[,] weights = Matrix.CalculateWeights();
  55. var point = Matrix.FindMaxWeightPoint(weights);
  56. var reducedMatrix = Matrix.Reduce(point.Item1, point.Item2);
  57. var unincludeMatrix = new ReducableMatrix(Matrix);
  58. unincludeMatrix[point.Item1, point.Item2] = null;
  59. Left = new SolutionNode(reducedMatrix, this, Value, true);
  60. Right = new SolutionNode(unincludeMatrix, this, Value + weights[point.Item1, point.Item2], false); //3 -- штраф за вес
  61. }
  62. public bool IsSolved()
  63. {
  64. return Matrix.GetLength(0) == 0;
  65. }
  66. public override string ToString()
  67. {
  68. return new StringBuilder().Append($"({(Value == null ? "∞" : Value.ToString())})").AppendLine().Append(Matrix.ToString()).ToString();
  69. }
  70. }
  71. }