Cod sursa(job #2424657)

Utilizator richard26Francu Richard richard26 Data 23 mai 2019 17:07:36
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <bits/stdc++.h>

using namespace std;

const int nMax = 50010;
const int costMax = 250010;

ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

vector < pair <int, int> > A[nMax];
set < pair <int, int> > S;
int cost[nMax];



int main()
{
    int N, M;
    f >> N >> M;
    for (int i = 0; i < M; i++)  {
      int x, y, c;
      f >> x >> y >> c;
      A[x].push_back(make_pair(y, c));
    }

    for (int i = 2; i <= N; i++) {
      S.insert(make_pair(costMax, i));
      cost[i] = costMax;
    }

    S.insert(make_pair(0, 1));

    for (int i = 1; i <= N; i++) {
      pair <int, int> p = *S.begin();
      int node = p.second;
      S.erase(p);

      for (auto it : A[node]) {
        if (cost[it.first] > cost[node] + it.second) {
          S.erase(make_pair(cost[it.first], it.first)) ;
          cost[it.first] = cost[node] + it.second;
          S.insert(make_pair(cost[it.first], it.first));
        }
      }
    }

    for (int i = 2; i <= N; i++) {
      if (cost[i] != costMax) {
        g << cost[i] << " ";
      } else {
        g << "0 ";
      }
    }

    return 0;

}