Реализовать алгоритм Краскала - Lisp

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

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

Добрый день, друзьяшки. Помогите пожалуйста, кому не будет трудным Препод дал такое задание:
Напишите две компьютерные программы (На С++ и на lisp (или на F#)), решающие следующую задачу: Связный граф задан списком ребер. Каждое ребро представляет собой тройку (вершина, вершина, длина). Граф неориентированный. Найти минимальное остовное дерево (в виде списка образующих его ребер).
Сделал это задание на C++, но лисп вобще не знаю, можете пожалуйста написать?)
Листинг программы
  1. #include <iostream>
  2. #include <list>
  3. #include <limits>
  4. #include <iomanip>
  5. #include <algorithm>
  6. #include <iterator>
  7. #include <vector>
  8. #include <windows.h>
  9. using namespace std;
  10. #ifdef max
  11. #undef max
  12. #endif
  13. class Graph
  14. {
  15. struct edge
  16. {
  17. unsigned vertex1, vertex2, length;
  18. };
  19. list<edge> graph;
  20. unsigned vertexes, highestVertex;
  21. void correctInput(unsigned& arg)
  22. {
  23. while (!(cin >> arg))
  24. {
  25. cout << "\nНекорректный ввод, повторите попытку:" << endl;
  26. cin.clear();
  27. cin.sync();
  28. cin.ignore(numeric_limits<streamsize>::max(), '\n');
  29. }
  30. }
  31. void addEdge(void)
  32. {
  33. edge tempObj;
  34. graph.push_back(tempObj);
  35. system("cls");
  36. cout << "Производится ввод " << graph.size()
  37. << "-ого ребра...\n" << endl;
  38. cout << "Введите 1-ую вершину:" << endl;
  39. correctInput(graph.back().vertex1);
  40. cout << "Введите 2-ую вершину:" << endl;
  41. correctInput(graph.back().vertex2);
  42. cout << "Введите вес ребра:" << endl;
  43. correctInput(graph.back().length);
  44. if (graph.back().vertex1 > highestVertex)
  45. highestVertex = graph.back().vertex1;
  46. if (graph.back().vertex2 > highestVertex)
  47. highestVertex = graph.back().vertex2;
  48. system("cls");
  49. }
  50. public:
  51. static struct sortFunctor
  52. {
  53. bool operator() (const edge& arg1, const edge& arg2)
  54. {
  55. return arg1.length < arg2.length;
  56. }
  57. } sortObj;
  58. Graph(void) : vertexes(0), highestVertex(0)
  59. { }
  60. Graph(unsigned arg) : vertexes(arg), highestVertex(0)
  61. { }
  62. friend istream& operator>>(istream&, Graph&);
  63. friend ostream& operator<<(ostream&, const Graph&);
  64. };
  65. Graph::sortFunctor Graph::sortObj;
  66. istream& operator>>(istream& arg1, Graph& arg2)
  67. {
  68. if (!arg2.vertexes)
  69. {
  70. system("cls");
  71. cout << "Граф пустой, введите число его ребер:" << endl;
  72. arg2.correctInput(arg2.vertexes);
  73. }
  74. if (arg2.vertexes)
  75. {
  76. for (unsigned i(0); i < arg2.vertexes; i++)
  77. arg2.addEdge();
  78. system("cls");
  79. arg2.graph.sort(Graph::sortObj);
  80. }
  81. return arg1;
  82. }
  83. ostream& operator<<(ostream& arg1, const Graph& arg2)
  84. {
  85. vector<bool> table(arg2.highestVertex, false);
  86. system("cls");
  87. cout << "Ребра минимального остовного дерева:\n" << endl;
  88. for (unsigned i(0); i++ < 45; cout.put('-'));
  89. cout.put('\n');
  90. cout << setw(15) << "Вершина 1" << setw(3) << '|'
  91. << setw(12) << "Вершина 2" << setw(7) << '|'
  92. << setw(8) << "Вес" << endl;
  93. for (unsigned i(0); i++ < 45; cout.put('-'));
  94. cout.put('\n');
  95. list<Graph::edge>::const_iterator iter(arg2.graph.begin());
  96. for (; iter != arg2.graph.end(); iter++)
  97. {
  98. static unsigned index1, index2;
  99. index1 = iter->vertex1 - 1;
  100. index2 = iter->vertex2 - 1;
  101. if (!table[index1] || !table[index2])
  102. {
  103. table[index1] = true;
  104. table[index2] = true;
  105. cout << setw(15) << iter->vertex1
  106. << setw(3) << '|' << setw(12) << iter->vertex2
  107. << setw(7) << '|' << setw(8) << iter->length << endl;
  108. }
  109. }
  110. for (unsigned i(0); i++ < 45; cout.put('-'));
  111. return arg1;
  112. }
  113. int main(void)
  114. {
  115. SetConsoleCP(1251);
  116. SetConsoleOutputCP(1251);
  117. Graph gr(0);
  118. cin >> gr;
  119. cout << gr << endl;
  120. system("pause");
  121. return 0;
  122. }

Решение задачи: «Реализовать алгоритм Краскала»

textual
Листинг программы
  1. ;; Проверить ребро
  2.  
  3. (defun chk-vert (v s)
  4.   (let ((a1 (car v))
  5.         (a2 (cadr v)))
  6.     (not (forsome s (lambda (w) (and (member a1 w) (member a2 w)))))))
  7.        
  8. ;; Добавление очередного ребра в "лес"        
  9.        
  10. (defun ins-vert (v w)        
  11.   (let* ((a1 (car v))
  12.          (a2 (cadr v))
  13.          (w1 (car (remove-if-not (lambda (x) (member a1 x)) w)))
  14.          (w2 (car (remove-if-not (lambda (x) (member a2 x)) w))))
  15.     (cond ((and (null w1) (null w2)) (cons (butlast v) w))
  16.           ((null w1) (cons (cons a1 w2) (remove-if (lambda (x) (member a2 x)) w)))
  17.           ((null w2) (cons (cons a2 w1) (remove-if (lambda (x) (member a1 x)) w)))
  18.           (t (cons (append w1 w2) (remove-if (lambda (x) (or (member a1 x) (member a2 x))) w))))))
  19.  
  20.  
  21. ;; Очередной шаг
  22.    
  23. (defun action (graph &optional (w nil) (r nil))
  24.   (cond ((null graph) r)
  25.         ((chk-vert (car graph) w) (action (cdr graph) (ins-vert (car graph) w) (append r (list (car graph)))))
  26.         (t (action (cdr graph) w r))))
  27.        
  28. (defun kruskal (graph)
  29.   (let ((g (qsort-a graph (lambda (x) (nth 2 x)))))
  30.      (action g)))

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


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

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

8   голосов , оценка 3.5 из 5

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

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

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