Cod sursa(job #2919791)

Utilizator AlexandruBenescuAlexandru Benescu AlexandruBenescu Data 19 august 2022 18:22:22
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <bits/stdc++.h>
#define INF 1000000001
#define L 50005
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

vector <pair <int, int>> G[L];
priority_queue <pair <int, int>> pq;
int dist[L], n;

void dijkstra(int src){
  int i, node, cost;
  for (i = 1; i <= n; i++)
    dist[i] = INF;
  dist[src] = 0;
  pq.push({-dist[src], src});
  while (!pq.empty()){
    cost = -pq.top().first;
    node = pq.top().second;
    pq.pop();
    if (cost == dist[node])
      for (auto it : G[node])
        if (cost + it.second < dist[it.first]){
          dist[it.first] = cost + it.second;
          pq.push({-dist[it.first], it.first});
        }
  }
  for (i = 1; i <= n; i++)
    if (dist[i] == INF)
      dist[i] = 0;
}

int main(){
  int m, i, a, b, c, src;
  fin >> n >> m;
  for (i = 0; i < m; i++){
    fin >> a >> b >> c;
    G[a].push_back({b, c});
  }
  src = 1;
  dijkstra(src);
  for (i = 1; i <= n; i++)
    if (i != src)
      fout << dist[i] << " ";
  fout << "\n";
  return 0;
}