Back to track
#71 Hard Advanced

Graph: Dijkstra

Open the editor

Problem

Shortest path in weighted graph.

Constraints

1 <= N, M <= 200000
Weights non-negative

Hints

  1. 1

    Priority queue

  2. 2

    Relax edges

Worked solution

Reference solution

One correct implementation. Alternative approaches that satisfy the constraints are equally valid — the reviewer judges behaviour, not style.

#include <bits/stdc++.h>
using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n, m; cin >> n >> m;
  vector<vector<pair<int,int>>> g(n);
  for (int i = 0; i < m; i++) {
    int u, v, w; cin >> u >> v >> w;
    g[u].push_back({v, w});
    g[v].push_back({u, w});
  }
  int src; cin >> src;
  const long long INF = 4e18;
  vector<long long> dist(n, INF);
  priority_queue<pair<long long,int>, vector<pair<long long,int>>, greater<pair<long long,int>>> pq;
  dist[src] = 0; pq.push({0, src});
  while (!pq.empty()) {
    auto [d, u] = pq.top(); pq.pop();
    if (d != dist[u]) continue;
    for (auto [v, w] : g[u]) {
      if (dist[v] > d + w) {
        dist[v] = d + w;
        pq.push({dist[v], v});
      }
    }
  }
  for (int i = 0; i < n; i++) {
    if (i) cout << ' ';
    cout << (dist[i] == INF ? -1 : dist[i]);
  }
  cout << '\n';
  return 0;
}

© 2026 ChitChat