Cod sursa(job #3197002)

Utilizator PatruMihaiPatru Mihai PatruMihai Data 25 ianuarie 2024 11:29:26
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <bits/stdc++.h>

using namespace std;

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

int main()
{
    int n, m;
    fin >> n >> m;

    vector<vector<pair<int, int>>> v(n + 1);
    vector<bool> viz(n + 1);
    vector<int> dist(n + 1, INT_MAX);

    dist[1]= 0;

    for(int i = 1; i <= m; i++)
    {
        int x, y, cost;
        fin >> x >> y >> cost;
        v[x].emplace_back(y, cost);
    }

    priority_queue<pair<int, int>> pq;

    pq.emplace(0, 1);

    while (!pq.empty())
    {
        int nod = pq.top().second;
        pq.pop();

        if(!viz[nod])
        {
            viz[nod] = true;

            for(auto it : v[nod])
            {
                if(dist[nod] + it.second < dist[it.first])
                {
                    dist[it.first] = dist[nod] + it.second;
                    pq.emplace(-dist[it.first], it.first);
                }
            }
        }
    }

    for(int i = 2; i <= n; i++)
    {
        if(dist[i] == INT_MAX)
            fout << "0 ";
        else
            fout << dist[i] << " ";
    }

    return 0;
}