From 0e050969c8ba9e9617465e7101b7f0eba5c2e611 Mon Sep 17 00:00:00 2001 From: anqude Date: Sat, 7 Jun 2025 07:08:01 +0000 Subject: [PATCH] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20main.cpp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.cpp | 107 ++++++++++++++++++++++++++----------------------------- 1 file changed, 51 insertions(+), 56 deletions(-) diff --git a/main.cpp b/main.cpp index 7942edb..5fe4e3a 100644 --- a/main.cpp +++ b/main.cpp @@ -1,91 +1,86 @@ #include #include #include -#include - +#include +#include using namespace std; -const int INF = numeric_limits::max(); // Представляет "бесконечность" +const int INF = numeric_limits::max(); -// Функция для поиска вершины с минимальным расстоянием -int minDistance(const vector& dist, const vector& visited) { - int minDist = INF; - int minIndex = -1; - - for (size_t i = 0; i < dist.size(); ++i) - if (!visited[i] && dist[i] < minDist) - minDist = dist[i], minIndex = i; - - return minIndex; -} - -// Алгоритм Дейкстры -void dijkstra(const vector>& graph, int start, int end) { - int n = graph.size(); - vector dist(n, INF); // Расстояния до вершин - vector parent(n, -1); // Для восстановления пути - vector visited(n, false); // Посещённые вершины +// Функция алгоритма Дейкстры +void dijkstra(const vector>& graph, int start, int end, int n) { + vector dist(n, INF); // Расстояния до вершин + vector prev(n, -1); // Предыдущие вершины для восстановления пути + vector visited(n, false); // Посещённые вершины dist[start] = 0; + priority_queue, vector>, greater>> pq; + pq.push({0, start}); - for (int count = 0; count < n - 1; ++count) { - int u = minDistance(dist, visited); - if (u == -1) break; // Недостижимые узлы + while (!pq.empty()) { + int u = pq.top().second; + pq.pop(); + + if (visited[u]) continue; visited[u] = true; - for (int v = 0; v < n; ++v) - if (!visited[v] && graph[u][v] && dist[u] != INF && dist[u] + graph[u][v] < dist[v]) { - dist[v] = dist[u] + graph[u][v]; - parent[v] = u; + for (int v = 0; v < n; ++v) { + if (graph[u][v] != -1 && !visited[v]) { + int newDist = dist[u] + graph[u][v]; + if (newDist < dist[v]) { + dist[v] = newDist; + prev[v] = u; + pq.push({dist[v], v}); + } } + } } - // Восстанавливаем путь if (dist[end] == INF) { - cout << "Путь из вершины " << start << " в вершину " << end << " не существует." << endl; - return; + cout << "Путь не существует." << endl; + } else { + cout << "Кратчайший путь: "; + vector path; + for (int v = end; v != -1; v = prev[v]) + path.push_back(v); + + reverse(path.begin(), path.end()); + for (size_t i = 0; i < path.size(); ++i) { + cout << path[i]+1; + if (i != path.size() - 1) + cout << " -> "; + } + cout << endl; + cout << "Суммарная стоимость: " << dist[end] << endl; } - - vector path; - int current = end; - while (current != -1) { - path.push_back(current); - current = parent[current]; - } - - cout << "Кратчайший путь из вершины " << start << " в вершину " << end << ":" << endl; - for (auto it = path.rbegin(); it != path.rend(); ++it) - cout << *it << (next(it) != path.rend() ? " -> " : ""); - - cout << "\nСуммарная стоимость пути: " << dist[end] << endl; } int main() { - setlocale(LC_ALL, "Russian"); + setlocale(LC_ALL, "ru"); int n; - cout << "Введите количество вершин: "; + cout << "Введите количество вершин графа: "; cin >> n; vector> graph(n, vector(n)); - cout << "Введите матрицу смежности (веса, 0 - отсутствие ребра):" << endl; - for (int i = 0; i < n; ++i) - for (int j = 0; j < n; ++j) + cout << "Введите матрицу смежности (" << -1 << " — нет ребра, 0 — петля, >0 — вес):" << endl; + for (int i = 0; i < n; ++i) { + for (int j = 0; j < n; ++j) { cin >> graph[i][j]; + } + } int start, end; - cout << "Введите начальную вершину: "; - cin >> start; - cout << "Введите конечную вершину: "; - cin >> end; + cout << "Начальная и конечная вершины (1-" << n << "): "; + cin >> start >> end; - if (start < 0 || start >= n || end < 0 || end >= n) { - cout << "Ошибка: номер вершины вне диапазона!" << endl; + if (start < 1 || start >= n+1 || end < 1 || end >= n+1) { + cout << "Некорректный ввод вершин." << endl; return 1; } - dijkstra(graph, start, end); + dijkstra(graph, start-1, end-1, n); return 0; } \ No newline at end of file