Advertisement
Bibodui

ЯМП Лаба 3 2023 (Графы)

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