Cod sursa(job #3320445)

Utilizator vvalentinCiun Valentin vvalentin Data 5 noiembrie 2025 20:24:34
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <bits/stdc++.h>
#define ll long long
#define pii pair<int, int>
#define INF 0x3f3f3f3f3f3f3f3f
using namespace std;
const int NMAX = 5e2;

struct node {
  int node;
  ll cost;
};

bool operator < (const node & a, const node & b) {
  return a.cost > b.cost;
}

int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0); cout.tie(0);
  #ifndef ONLINE_JUDGE
  freopen("dijkstra.in", "r", stdin);
  freopen("dijkstra.out", "w", stdout);
  #endif

  int n, m, a, b, c;
  cin >> n >> m;
  vector<vector<node>> v(n + 1);
  vector<ll> dist(n + 1, INF);
  while (m--) {
    cin >> a >> b >> c;
    v[a].push_back({b, c});
  }
  priority_queue<node> pq;
  pq.push({1, 0});
  while (pq.size()) {
    while (pq.size() && dist[pq.top().node] != INF) pq.pop();
    if (pq.size()) {
      node nod = pq.top();
      pq.pop();
      dist[nod.node] = nod.cost;
      for (node i : v[nod.node]) {
        if (dist[i.node] == INF) pq.push({i.node, i.cost + dist[nod.node]});
      }
    } 
  }
  for (int i = 2; i <= n; i++) {
    if (dist[i] == INF) dist[i] = 0;
    cout << dist[i] << ' ';
  }
  return 0;
}