Skip to content

Instantly share code, notes, and snippets.

@merciless
Created April 2, 2019 12:55
Show Gist options
  • Save merciless/5905892139e398bba084571410691560 to your computer and use it in GitHub Desktop.
Save merciless/5905892139e398bba084571410691560 to your computer and use it in GitHub Desktop.
Алгоритм Дейкстры [работает не верно]
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class Dijkstra {
public:
const int MAX = 1000000;
int vertices;
int from, to;
int distanceToTarget;
int **graph;
// Конструктор
Dijkstra() {
cin >> vertices;
graph = new int*[vertices];
for (int i = 0; i < vertices; i++) {
graph[i] = new int[vertices];
}
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
cin >> graph[i][j];
}
}
cin >> from >> to;
from--;
to--;
}
// Поиск минимальной длины
int minDistance(int distanceance[], bool visited[]) {
int min = MAX;
int min_index;
for (int v = 0; v < vertices; v++) {
if (visited[v] == false && distanceance[v] <= min) {
min = distanceance[v];
min_index = v;
}
}
return min_index;
}
// Алгоритм
void algorithm() {
int* distance = new int[vertices];
bool* visited = new bool[vertices];
int* parents = new int[vertices];
for (int i = 0; i < vertices; i++)
{
distance[i] = MAX;
visited[i] = false;
}
distance[from] = 0;
for (int c = 0; c < vertices; c++)
{
int u = minDistance(distance, visited);
// cout << u << " ";
visited[u] = true;
for (int v = 0; v < vertices; v++)
{
if (!visited[v] && graph[u][v] && distance[u] != MAX && distance[u] + graph[u][v] < distance[v]) {
distance[v] = distance[u] + graph[u][v];
parents[v] = u;
}
}
if (c == to) {
if (distance[to] == MAX) {
cout << "0";
return;
}
distanceToTarget = distance[to];
cout << distanceToTarget << endl;
vector<int> path;
while (to != from) {
path.push_back(to + 1);
to = parents[to];
}
path.push_back(from + 1);
reverse(path.begin(), path.end());
for (auto i = path.begin(); i != path.end(); ++i)
cout << *i << ' ';
return;
}
}
}
};
int main() {
Dijkstra alg;
alg.algorithm();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment