Code : Dijkstra?
#include <bits/stdc++.h>
using namespace std;
const long long inf = (long long)1e12;
class Graph {
public:
int n;
vector<vector<pair<int, long long>>> adj;
Graph(int n) {
this->n = n;
adj.resize(n);
}
public:
void dijkstra();
};
void Graph ::dijkstra() {
int src = 0;
vector<long long> d(n, inf);
vector<int> parent(n);
set<pair<long long, int>> heap;
parent[src] = -1;
d[src] = 0;
for (int i = 0; i < n; i++) {
heap.insert({d[i], i});
}
for (int i = 0; i < n; i++) {
int v = heap.begin()->second;
heap.erase(heap.begin());
for (auto [c, w] : adj[v]) {
auto nxt = d[v] + w;
if (d[c] > nxt) {
heap.erase({d[c], c});
d[c] = nxt;
parent[c] = v;
heap.insert({d[c], c});
}
}
}
int dest = n - 1;
if (d[dest] >= inf) {
cout << -1 << endl;
return;
}
vector<int> res;
int now = dest;
while (now != -1) {
res.push_back(now);
now = parent[now];
}
reverse(res.begin(), res.end());
for (auto &ele : res) {
cout << ele + 1 << " ";
}
cout << endl;
}
void solve() {
int n, m;
cin >> n >> m;
Graph g(n);
for (int i = 0; i < m; i++) {
int x, y, w;
cin >> x >> y >> w;
x--;
y--;
g.adj[x].push_back({y, w});
g.adj[y].push_back({x, w});
}
g.dijkstra();
}
int main() {
solve();
return 0;
}
#include <bits/stdc++.h>
using namespace std;
const long long inf = (long long)1e12;
class Graph {
public:
int n;
vector<vector<pair<int, long long>>> adj;
Graph(int n) {
this->n = n;
adj.resize(n);
}
public:
void dijkstra() {
int src = 0;
vector<long long> wave_arrival_time(n, inf);
vector<bool> visited(n);
vector<int> parent(n);
parent[src] = -1;
wave_arrival_time[src] = 0;
// At every minute, a wave reaches a vertex for the first time, and
// that timestamp is the shortest path of that node from src.
// Hence, we only need to run this algorithm for n times.
for (int i = 0; i < n; i++) {
int vertex;
long long current_time = inf;
for (int v = 0; v < n; v++) {
if (!visited[v] && wave_arrival_time[v] < current_time) {
current_time = wave_arrival_time[v];
vertex = v;
}
}
visited[vertex] = true;
// Emit waves for all the neighbors.
for (auto [child, weight] : adj[vertex]) {
auto arrival_time_of_this_wave = current_time + weight;
// Ignore the wave if there's a faster wave that would arrive
// at the children.
if (wave_arrival_time[child] > arrival_time_of_this_wave) {
wave_arrival_time[child] = arrival_time_of_this_wave;
parent[child] = vertex;
}
}
}
int dest = n - 1;
if (wave_arrival_time[dest] >= inf) {
cout << -1 << endl;
return;
}
vector<int> res;
int now = dest;
while (now != -1) {
res.push_back(now);
now = parent[now];
}
reverse(res.begin(), res.end());
for (auto &ele : res) {
cout << ele + 1 << " ";
}
cout << endl;
}
};
void solve() {
int n, m;
cin >> n >> m;
Graph g(n);
for (int i = 0; i < m; i++) {
int x, y, w;
cin >> x >> y >> w;
x--;
y--;
g.adj[x].push_back({y, w});
g.adj[y].push_back({x, w});
}
g.dijkstra();
}
int main() {
solve();
return 0;
}