A country has n cities and m roads. Each road joins two cities and has a cost. Starting from city 1, find the cheapest cost to reach every city.
What to build
Run Dijkstra with a priority_queue of negated distances. Roads work in both directions. Print the distance to each city, or -1 for a city that cannot be reached.
Requirements
- Use Dijkstra, not Bellman-Ford
- Skip out-of-date queue entries
- Use
long longfor distances
Input
The first line has n and m. Each of the next m lines has a b w: a road between a and b with cost w.
Output
n numbers: the cheapest cost from city 1 to cities 1, 2, ..., n, with -1 for unreachable cities.
Constraints
1 ≤ n ≤ 2,000. 0 ≤ m ≤ 10,000. 1 ≤ w ≤ 10⁹.
Example
Input:
4 4
1 2 5
1 3 2
3 2 1
2 4 7
Output:
0 3 2 10
Why it works
Dijkstra always finishes the closest unprocessed city next, and since costs are not negative, its distance cannot improve later. Each road is relaxed at most twice, giving O((n + m) log n).
Examples
4 4 1 2 5 1 3 2 3 2 1 2 4 7
0 3 2 10
3 1 1 2 4
0 4 -1
Hints
Hint 1
vector<vector<pair<int, int> > > adj(n + 1); add the road to both ends.
Hint 2
Push {-dist, vertex}; when you pop, take d = -top.first and skip if d > dist[u].
Hint 3
Start dist at a big value like 4e18 (as long long) and print -1 where it stayed big.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<vector<pair<int, int> > > adj(n + 1);
for (int i = 0; i < m; i++) {
int a, b, w;
cin >> a >> b >> w;
adj[a].push_back(make_pair(b, w));
adj[b].push_back(make_pair(a, w));
}
const long long INF = 4000000000000000000LL;
vector<long long> dist(n + 1, INF);
priority_queue<pair<long long, int> > pq;
dist[1] = 0;
pq.push(make_pair(0LL, 1));
while (!pq.empty()) {
long long d = -pq.top().first;
int u = pq.top().second;
pq.pop();
if (d > dist[u]) continue;
for (size_t k = 0; k < adj[u].size(); k++) {
int v = adj[u][k].first;
long long w = adj[u][k].second;
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
pq.push(make_pair(-dist[v], v));
}
}
}
for (int v = 1; v <= n; v++) cout << (dist[v] == INF ? -1 : dist[v]) << " ";
cout << "\n";
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step