51 lines
1.3 KiB
C++
51 lines
1.3 KiB
C++
#include <vector>
|
|
#include <algorithm>
|
|
#include <iostream>
|
|
#include <queue>
|
|
#include <climits>
|
|
using namespace std;
|
|
|
|
void print(vector<int> tab) {
|
|
for (int el : tab)
|
|
cout << el << " ";
|
|
cout << endl;
|
|
}
|
|
|
|
void dijkstra(vector<vector<pair<int, int>>> &adjw, vector<int> &d, vector<int> &prev, vector<int> &prov, int n) {
|
|
int start = 0;
|
|
prov[start] = 0;
|
|
d[start] = 0;
|
|
prev[start] = -1;
|
|
while (1) {
|
|
int x = -1;
|
|
for (int y = 0; y < n; y++) {
|
|
if (prov[y] > -1) {
|
|
if (x == -1 || prov[y] < prov[x]) {
|
|
x = y;
|
|
}
|
|
}
|
|
}
|
|
if (x == -1)
|
|
break;
|
|
d[x] = prov[x];
|
|
prov[x] = -2;
|
|
for (auto[y, w] : adjw[x]) {
|
|
if (prov[y] == -1 || prov[y] > -1 && d[x] + w < prov[y]) {
|
|
prov[y] = d[x] + w;
|
|
prev[y] = x;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
vector<vector<pair<int, int>>> adjw = {{{1, 8}, {2, 12}}, {{2, 13}, {3, 25}}, {{6, 21}, {3, 14}}, {{6, 12}, {8, 16}, {7, 12}, {5, 8}, {4, 20}}, {{1, 9}, {5, 19}}, {{7, 11}}, {{8, 11}}, {{8, 9}}, {}};
|
|
int n = adjw.size();
|
|
vector<int> d(n, -1);
|
|
vector<int> prev(n, -1);
|
|
vector<int> prov(n, -1);
|
|
dijkstra(adjw, d, prev, prov, n);
|
|
print(d);
|
|
print(prev);
|
|
}
|
|
|