Created
April 2, 2019 12:55
-
-
Save merciless/5905892139e398bba084571410691560 to your computer and use it in GitHub Desktop.
Алгоритм Дейкстры [работает не верно]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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