Advertisement
Bibodui

graf

Jun 5th, 2023 (edited)
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.19 KB | None | 0 0
  1. //Пример входного файла "graph.txt":
  2. //Количество вершин
  3. //Исходная вершина
  4. //u v weight
  5. //u v weight
  6. //
  7. //где u - исходная вершина, v - конечная, weight - вес ребра
  8.  
  9.  
  10. #include <iostream>
  11. #include <fstream>
  12. #include <vector>
  13. #include <limits>
  14.  
  15. using namespace std;
  16.  
  17. int INF = numeric_limits<int>::max(); // Значение "бесконечность"
  18.  
  19. // Структура для представления ребра графа
  20. struct Edge
  21. {
  22. int destination; // Вершина, в которую ведет ребро
  23. int weight; // Вес ребра
  24. };
  25.  
  26. void floyd_warshall_algorithm(vector<vector<Edge>>& graph, int number_of_vertices, vector<vector<int>>& distances)
  27. {
  28. // Элементы на диагонали матрицы расстояний равны 0
  29. for (int i = 0; i < number_of_vertices; i++)
  30. distances[i][i] = 0;
  31.  
  32. // Заполнение матрицы расстояний из графа
  33. for (int u = 0; u < number_of_vertices; u++)
  34. for (Edge edge : graph[u])
  35. distances[u][edge.destination] = edge.weight;
  36.  
  37. // Вычисление кратчайших путей между всеми парами вершин
  38. for (int k = 0; k < number_of_vertices; k++)
  39. for (int i = 0; i < number_of_vertices; i++)
  40. for (int j = 0; j < number_of_vertices; j++)
  41. // Если путь через вершину k короче текущего пути, обновляем его
  42. if (distances[i][k] != INF && distances[k][j] != INF && distances[i][k] + distances[k][j] < distances[i][j])
  43. distances[i][j] = distances[i][k] + distances[k][j];
  44. }
  45.  
  46. // Обход графа в глубину
  47. void DFS(vector<vector<Edge>>& graph, int vertex, vector<bool>& visited)
  48. {
  49. visited[vertex] = true; // Помечаем текущую вершину как посещенную
  50. cout << vertex << " "; // Выводим текущую вершину
  51.  
  52. // Рекурсивно обходим все соседние вершины
  53. for (Edge edge : graph[vertex])
  54. {
  55. int next_vertex = edge.destination;
  56. if (!visited[next_vertex])
  57. {
  58. DFS(graph, next_vertex, visited);
  59. }
  60. }
  61. }
  62.  
  63.  
  64. int main()
  65. {
  66. setlocale(LC_ALL, "rus");
  67. ifstream file("graph.txt");
  68. if (!file)
  69. {
  70. cout << "Не удалось открыть файл." << endl;
  71. return -1;
  72. }
  73.  
  74. int number_of_vertices;
  75. file >> number_of_vertices; // Считываем количество вершин графа
  76.  
  77. vector<vector<Edge>> graph(number_of_vertices); // Граф, представленный списком смежности
  78.  
  79. int source; // Исходная вершина
  80. file >> source;
  81.  
  82. // Считываем данные о ребрах графа из файла
  83. int u, v, weight;
  84. while (file >> u >> v >> weight)
  85. {
  86. graph[u].push_back({ v, weight });
  87. }
  88.  
  89. file.close();
  90.  
  91. // Инициализация матрицы расстояний
  92. vector<vector<int>> distances(number_of_vertices, vector<int>(number_of_vertices, INF));
  93. floyd_warshall_algorithm(graph, number_of_vertices, distances);
  94.  
  95. // Вывод кратчайших путей
  96. cout << ' ' << '\t';
  97. for (int i = 0; i < number_of_vertices; i++)
  98. cout << i << '\t';
  99. cout << endl << endl;
  100. for (int i = 0; i < number_of_vertices; i++)
  101. {
  102. cout << i << '\t';
  103. for (int j = 0; j < number_of_vertices; j++)
  104. {
  105. if (distances[i][j] == INF)
  106. {
  107. cout << "нет пути" << '\t';
  108. }
  109. else
  110. {
  111. cout << distances[i][j] << '\t';
  112. }
  113. }
  114. cout << endl;
  115. }
  116.  
  117. cout << endl;
  118. cout << "//////////////////////////////" << endl;
  119. cout << endl;
  120.  
  121. cout << "Обход в глубину: ";
  122. vector<bool> visited(number_of_vertices, false);
  123. DFS(graph, source, visited);
  124. cout << endl;
  125.  
  126. return 0;
  127. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement