Задача о порядке перемножения матриц - C#

Узнай цену своей работы

Формулировка задачи:

Алгоритм здесь https://ru.wikipedia.org/wiki/%D0%97...80%D0%B8%D1%86 Сам алгоритм понятен, но непонятна реализация как бы глупо это не звучало. Пробовал сделать вот так
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace matrixchainconsole
  7. {
  8. public class DataStore
  9. {
  10. public List<List<int>> m; //матрица m
  11. public List<List<int>> s; //матрица s
  12. public List<List<int>> result=new List<List<int>>(); //результат всех перемножений
  13. public List<List<List<int>>> source=new List<List<List<int>>>(); //массив из 2-мерных матриц (A0,A1,...,An) которые нужно перемножить
  14. public List<int> sizes = new List<int>(); //размеры матриц (записаны таким образом - 12,10,7,4 => значит 3 матрицы размерами 12x10,10x7,7x4)
  15. public string order = new string('a', 0); //правильное расположение скобок
  16. public DataStore(List<int> l)
  17. {
  18. sizes = l;
  19. }
  20. }
  21. public class Class
  22. {
  23. public DataStore dataStore;
  24. public Class(DataStore d)
  25. {
  26. dataStore = d;
  27. }
  28. public void matrixChainOrder()
  29. {
  30. int n = dataStore.sizes.Count - 1;
  31. //выделяем память под матрицы m и s
  32. dataStore.m = new List<List<int>>();
  33. dataStore.s = new List<List<int>>();
  34. for (int i = 0; i < n; i++)
  35. {
  36. dataStore.m.Add(new List<int>());
  37. dataStore.s.Add(new List<int>());
  38. //заполняем нулевыми элементами
  39. for (int a = 0; a < n; a++)
  40. {
  41. dataStore.m[i].Add(0);
  42. dataStore.s[i].Add(0);
  43. }
  44. }
  45. //выполняем итерационный алгоритм
  46. int j;
  47. for (int l = 1; l < n; l++)
  48. for (int i = 0; i < n - l; i++)
  49. {
  50. j = i + l;
  51. dataStore.m[i][j] = int.MaxValue;
  52. for (int k = i; k < j; k++)
  53. {
  54. int q = dataStore.m[i][k] + dataStore.m[k + 1][j] +
  55. dataStore.sizes[i] * dataStore.sizes[k + 1] * dataStore.sizes[j + 1];
  56. if (q < dataStore.m[i][j])
  57. {
  58. dataStore.m[i][j] = q;
  59. dataStore.s[i][j] = k;
  60. }
  61. }
  62. }
  63. }
  64. //метод - простое перемножение 2-х матриц
  65. public List<List<int>> matrixMultiply(List<List<int>> A, List<List<int>> B)
  66. {
  67. int rowsA = A.Count;
  68. int columnsB = B[0].Count;
  69. //column count of A == rows count of B
  70. int columnsA = B.Count;
  71. //memory alloc for "c"
  72. List<List<int>> c = new List<List<int>>();
  73. for (int i = 0; i < rowsA; i++)
  74. {
  75. c.Add(new List<int>());
  76. for (int a = 0; a < columnsB; a++)
  77. {
  78. c[i].Add(0);
  79. }
  80. }
  81. //do multiplying
  82. for (int i = 0; i < rowsA; i++)
  83. for (int j = 0; j < columnsB; j++)
  84. for (int k = 0; k < columnsA; k++)
  85. c[i][j] += A[i][k] * B[k][j];
  86. //return value
  87. return c;
  88. }
  89. //метод, который непосредственно выполняет перемножение в правильном порядке
  90. //первоначально вызывается таким образом
  91. //dataStore.result = matrixChainMultiply(0, dataStore.sizes.Count - 2);
  92. public List<List<int>> matrixChainMultiply(int i, int j)
  93. {
  94. if (j > i)
  95. {
  96. List<List<int>> x = matrixChainMultiply(i, dataStore.s[i][j]);
  97. List<List<int>> y = matrixChainMultiply(dataStore.s[i][j] + 1, j);
  98. return matrixMultiply(x, y);
  99. }
  100. else return dataStore.source[i];
  101. }
  102. //метод печатающий строку с правильной расстановкой скобок
  103. public void printOrder(int i, int j)
  104. {
  105. if (i == j) dataStore.order += "A" + i.ToString();
  106. else
  107. {
  108. dataStore.order += "(";
  109. printOrder(i, dataStore.s[i][j]);
  110. dataStore.order += "*";
  111. printOrder(dataStore.s[i][j] + 1, j);
  112. dataStore.order += ")";
  113. }
  114. }
  115. }
  116. class Program
  117. {
  118. static void Main(string[] args)
  119. {
  120. List<int> list = new List<int>();
  121. list.Add(12);
  122. list.Add(10);
  123. list.Add(7);
  124. list.Add(4);
  125. DataStore d=new DataStore(list);
  126. Class c = new Class(d);
  127. c.matrixChainOrder();
  128. c.dataStore.result= c.matrixChainMultiply(0,c.dataStore.sizes.Count-2);
  129.  
  130. }
  131. }
  132. }
Но что-то не получается и не работает. Подскажите что исправить. Заранее благодарен.

Решение задачи: «Задача о порядке перемножения матриц»

textual
Листинг программы
  1.     class Program
  2.     {
  3.         static void Main(string[] args)
  4.         {
  5.             List<int> list = new List<int>();
  6.             list.Add(12);
  7.             list.Add(10);
  8.             list.Add(7);
  9.             list.Add(4);
  10.             DataStore d = new DataStore(list);
  11.             Class c = new Class(d);
  12.             c.matrixChainOrder();
  13.             c.printOrder(0, 2);
  14.             Console.WriteLine(d.order);
  15.             //c.dataStore.result = c.matrixChainMultiply(0, c.dataStore.sizes.Count - 2);
  16.  
  17.             Console.ReadLine();
  18.         }
  19.     }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

14   голосов , оценка 3.857 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы