Cod sursa(job #3355752)

Utilizator horia_Horia Casuneanu horia_ Data 25 mai 2026 17:41:15
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, m;
const long long INF = 1e12;
long long dist[50005];
bool viz[50005];
vector<pair<int, int>> muchii[50005];
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;

void Dijkstra()
{
    for (int i = 1; i <= n; ++i)
        dist[i] = INF;
    dist[1] = 0;
    pq.push({0, 1});
    while (! pq.empty())
    {
        int nod = pq.top().second;
        pq.pop();
        if (viz[nod] != 0)
            continue;
        viz[nod] = 1;
        for (pair<int, int> i : muchii[nod])
        {
            int fiu = i.first;
            long long cost = dist[nod] + i.second;
            if (cost < dist[fiu])
            {
                dist[fiu] = cost;
                pq.push({dist[fiu], fiu});
            }
        }
    }
}

int main()
{
    fin >> n >> m;
    for (int i = 1; i <= m; ++i)
    {
        int a, b, c;
        fin >> a >> b >> c;
        muchii[a].push_back({b, c});
    }
    Dijkstra();
    for (int i = 2; i <= n; ++i)
    {
        if (dist[i] != INF)
            fout << dist[i] << ' ';
        else
            fout << 0 << ' ';
    }
    return 0;
}