Загрузка данных
.h
#pragma once
#include <iostream>
#include <vector>
#include <string>
class task5_22 {
private:
int vertices;
std::vector<std::vector<int>> adjMatrix;
public:
task5_22(int v);
void loadFromFile(const std::string& filename);
void dfs_stack(int start, std::ostream& os) const;
void dijkstra(int start, const std::string& outputFile) const;
friend std::ostream& operator<<(std::ostream& os, const task5_22& g);
task5_22& operator=(const task5_22& other);
};
------------------------------------------------------------------
List.cpp
#include "task5_22.h"
#include <fstream>
#include <stack>
#include <queue>
#include <limits>
#include <functional>
#include <string>
using namespace std;
task5_22::task5_22(int v) : vertices(v) {
adjMatrix.assign(v, vector<int>(v, numeric_limits<int>::max()));
for (int i = 0; i < v; ++i) adjMatrix[i][i] = 0;
}
// Чтение списка ребер (формат: u v weight)
void task5_22::loadFromFile(const string& filename) {
ifstream in(filename);
if (!in) {
cerr << "Ошибка: Не удалось открыть файл " << filename << endl;
exit(1);
}
int u, v, w;
// Читаем до конца файла
while (in >> u >> v >> w) {
if (u >= 0 && u < vertices && v >= 0 && v < vertices) {
// Для ненаправленного графа
adjMatrix[u][v] = w;
adjMatrix[v][u] = w;
}
}
}
void task5_22::dfs_stack(int start, ostream& os) const {
vector<bool> visited(vertices, false);
stack<int> st;
st.push(start);
while (!st.empty()) {
int cur = st.top();
st.pop();
if (!visited[cur]) {
visited[cur] = true;
os << cur << " ";
// Добавляем соседей в обратном порядке для корректного обхода
for (int i = vertices - 1; i >= 0; --i) {
if (adjMatrix[cur][i] != numeric_limits<int>::max() &&
adjMatrix[cur][i] != 0 && !visited[i]) {
st.push(i);
}
}
}
}
os << endl;
}
void task5_22::dijkstra(int start, const string& outputFile) const {
vector<int> dist(vertices, numeric_limits<int>::max());
dist[start] = 0;
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;
pq.push({0, start});
while (!pq.empty()) {
int d = pq.top().first;
int u = pq.top().second;
pq.pop();
if (d > dist[u]) continue;
for (int v = 0; v < vertices; ++v) {
int w = adjMatrix[u][v];
if (w != numeric_limits<int>::max() && w != 0) {
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
pq.push({dist[v], v});
}
}
}
}
ofstream out(outputFile);
for (int i = 0; i < vertices; ++i) {
out << "Расстояние до вершины " << i << ": "
<< (dist[i] == numeric_limits<int>::max() ? "INF" : to_string(dist[i])) << endl;
}
}
ostream& operator<<(ostream& os, const task5_22& g) {
g.dfs_stack(0, os);
return os;
}
task5_22& task5_22::operator=(const task5_22& other) {
if (this != &other) {
vertices = other.vertices;
adjMatrix = other.adjMatrix;
}
return *this;
}
--------------------
main.cpp
#include "task5_22.h"
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
int main(int argc, char* argv[]) {
// Настройка кодировки для русского языка
SetConsoleOutputCP(1251);
cout << "========================================" << endl;
cout << "Студент: Карташов Дмитрий Анатольевич" << endl;
cout << "Группа: БББО-25-25" << endl;
cout << "Вариант: 22" << endl;
cout << "========================================" << endl;
cout << endl;
if (argc != 4) {
cout << "Ошибка: Неверное количество аргументов." << endl;
cout << "Использование: app.exe <вершины> <рёбра> <файл_данных>" << endl;
cout << "Пример: app.exe 5 7 data.txt" << endl;
return 1;
}
int v = stoi(argv[1]);
// int e = stoi(argv[2]); // Количество ребер считывается автоматически из файла
string fileName = argv[3];
cout << "Параметры графа:" << endl;
cout << "Вершин: " << v << endl;
cout << "Загрузка данных (Список ребер) из файла: " << fileName << "..." << endl;
task5_22 graph(v);
graph.loadFromFile(fileName);
cout << "Обход в глубину (стек): ";
cout << graph;
cout << endl;
cout << "Запуск алгоритма Дейкстры..." << endl;
graph.dijkstra(0, "result.txt");
cout << "Результаты кратчайших путей сохранены в result.txt" << endl;
cout << endl;
cout << "Проверка оператора присваивания (=):" << endl;
task5_22 copyGraph(0);
copyGraph = graph;
cout << "Обход копии графа: ";
cout << copyGraph;
cout << endl;
cout << "========================================" << endl;
cout << "Программа завершена успешно." << endl;
cout << "========================================" << endl;
return 0;
}
--------------------------------------
data.txt
0 1 5
0 2 4
0 3 3
1 3 14
2 3 7
2 4 9
3 4 12