MeGaDeTH_91

Knapsack

Jun 6th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.31 KB | None | 0 0
  1. namespace _01.KnapsackProblem
  2. {
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6.  
  7. public class StartUp
  8. {
  9. private static int capacity = 0;
  10. private static List<Item> allItems = new List<Item>();
  11. private static int[,] maxPrice;
  12. private static bool[,] takeItems;
  13.  
  14. public static void Main()
  15. {
  16. ReadInputInitialize();
  17.  
  18. TakeItems();
  19.  
  20. PrintResult();
  21. }
  22.  
  23. private static void PrintResult()
  24. {
  25. List<Item> chosen = new List<Item>();
  26.  
  27. int remainingCapacity = capacity;
  28.  
  29. for (int i = allItems.Count; i > 0; i--)
  30. {
  31. if(takeItems[i, remainingCapacity])
  32. {
  33. chosen.Add(allItems[i - 1]);
  34. remainingCapacity -= allItems[i - 1].Weight;
  35. }
  36. }
  37.  
  38. int totalWeight = chosen.Sum(x => x.Weight);
  39. int totalValue = chosen.Sum(x => x.Value);
  40.  
  41. Console.WriteLine($"Total Weight: {totalWeight}");
  42. Console.WriteLine($"Total Value: {totalValue}");
  43.  
  44. chosen = chosen.OrderBy(x => x.Name).ToList();
  45. Console.WriteLine(string.Join(Environment.NewLine, chosen.Select(x => x.Name)));
  46. }
  47.  
  48. private static void TakeItems()
  49. {
  50. for (int row = 1; row <= allItems.Count; row++)
  51. {
  52. Item item = allItems[row - 1];
  53.  
  54. for (int col = 1; col <= capacity; col++)
  55. {
  56. int takeValue = 0;
  57. int noTakeValue = maxPrice[row - 1, col];
  58.  
  59. if (item.Weight <= col)
  60. {
  61. takeValue = maxPrice[row - 1, col - item.Weight] + item.Value;
  62. }
  63.  
  64. if (takeValue > noTakeValue)
  65. {
  66. maxPrice[row, col] = takeValue;
  67. takeItems[row, col] = true;
  68. }
  69. else
  70. {
  71. maxPrice[row, col] = noTakeValue;
  72. }
  73. }
  74. }
  75. }
  76.  
  77. private static void ReadInputInitialize()
  78. {
  79. capacity = int.Parse(Console.ReadLine());
  80.  
  81. string line;
  82. while ((line = Console.ReadLine()) != "end")
  83. {
  84. string[] tokens = line
  85. .Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)
  86. .ToArray();
  87.  
  88. string name = tokens[0];
  89. int weight = int.Parse(tokens[1]);
  90. int value = int.Parse(tokens[2]);
  91.  
  92. Item item = new Item()
  93. {
  94. Name = name,
  95. Value = value,
  96. Weight = weight
  97. };
  98. allItems.Add(item);
  99. }
  100.  
  101. maxPrice = new int[allItems.Count + 1, capacity + 1];
  102. takeItems = new bool[allItems.Count + 1, capacity + 1];
  103. }
  104.  
  105. private class Item
  106. {
  107. public string Name { get; set; }
  108.  
  109. public int Value { get; set; }
  110.  
  111. public int Weight { get; set; }
  112. }
  113. }
  114. }
Advertisement
Add Comment
Please, Sign In to add comment