Cod sursa(job #3134134)

Utilizator Alex_HossuHossu Alexandru Alex_Hossu Data 28 mai 2023 15:59:43
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <bits/stdc++.h>

const int MAX_N = 5e4 + 5;
const int MY_INT_MAX = 1e9;

std::ifstream fin("dijkstra.in");
std::ofstream fout("dijkstra.out");

class PrqStr {
  public:
    int pos;
    int val;
    bool operator<(const PrqStr &other) const {
      return val < other.val;
    }
};

class Edge {
  public:
    int pos;
    int cost;
};

std::vector<Edge> web[MAX_N];

std::priority_queue<PrqStr> prq;
int dist[MAX_N];

void dijkstra(int start, int n) {
  PrqStr u;

  while (!prq.empty()) {
    u = prq.top();
    prq.pop();

    for (auto i : web[u.pos]) {
      if (dist[u.pos] + i.cost < dist[i.pos]) {
        prq.push({i.pos, dist[u.pos] + i.cost});
        dist[i.pos] = dist[u.pos] + i.cost;
      }
    }
  }
}

int main() {
  int n, p, i, j, c;

  fin >> n >> p;
  while (fin >> i >> j >> c)
    web[i].push_back({j, c});

  for (i = 1; i <= n; i++)
    if (i != p)
      dist[i] = MY_INT_MAX;
  prq.push({p, dist[p]});

  dijkstra(p, n);

  for (i = 1; i <= n; i++) {
    if (dist[i] == MY_INT_MAX)
      fout << -1;
    else
      fout << dist[i];
    fout << ' ';
  }

  return 0;
}