Cod sursa(job #3168563)

Utilizator David8406Marian David David8406 Data 12 noiembrie 2023 18:45:29
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <iostream>
#include <algorithm>
#include <fstream>
#include <vector>
#include <queue>
#include <stack>
#include <climits>
#include <set>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int n;
struct coada {
    int nod, cost;
    bool operator<(const coada& other) const {
        return (*this).cost > other.cost;
    }
};
vector<coada> v[50005];
int cost[50005];
priority_queue<coada> q;
void dijkstra(int nod) {
    for (int i = 1; i <= n; i++) cost[i] = 1e9;
    cost[nod] = 0;
    q.push({ nod,0 });
    while (!q.empty()) {
        coada cr = q.top();
        q.pop();
        if (cr.cost != cost[cr.nod]) continue;
        for (auto el : v[cr.nod]) {
            if (cost[el.nod] > cr.cost + el.cost) {
                cost[el.nod] = cr.cost + el.cost;
                q.push({ el.nod,cr.cost + el.cost });
            }
        }
    }
}
int main() {
    int m;
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y, c;
        fin >> x >> y >> c;
        v[x].push_back({ y,c });
    }
    dijkstra(1);
    for (int i = 2; i <= n; i++)
        if (cost[i] == 1e9) fout << 0 << " ";
    else fout << cost[i] << " ";
}