Cod sursa(job #3293755)

Utilizator mihai21681Maricutu Mihai Alexandru mihai21681 Data 12 aprilie 2025 15:11:04
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
// 12.04.2025.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");
typedef pair<int, int> PI;
const int INF = 0x3f3f3f3f;
int n, m, x, y, c, d[50001];
vector<PI> G[50001];
void dijk(int nod) {
    for (int i = 1; i <= n; i++)
        d[i] = INF;
    d[nod] = 0;
    priority_queue<PI, vector<PI>, greater<PI>> Q;
    Q.push({ 0, nod });
    while (!Q.empty()) {
        int nod = Q.top().second, cost = Q.top().first;
        Q.pop();
        if (d[nod] < cost) continue;
        for (PI q : G[nod]) {
            int newnod = q.first, newcost = q.second;
            if (d[newnod] > d[nod] + newcost) {
                d[newnod] = d[nod] + newcost;
                Q.push({ d[newnod], newnod });
            }
        }
    }
}
int main()
{
    cin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        cin >> x >> y >> c;
        G[x].push_back({y, c});
    }
    dijk(1);
    for (int i = 2; i <= n; i++)
        if (d[i] == INF) cout << "0 ";
        else cout << d[i] << ' ';
    return 0;
}