Cod sursa(job #2828997)

Utilizator robertanechita1Roberta Nechita robertanechita1 Data 8 ianuarie 2022 10:53:46
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>

using namespace std;

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

vector<pair<int, int>>h[100001];
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>>q;
int n, m, viz[100001], p;
int d[100001];

void Dijkstra(int p)
{
    for(int i = 0; i <= n; i++)
        d[i] = 1e9;
    d[p] = 0;
    q.push({0, p});
    while(!q.empty())
    {
        int cost = q.top().first;
        int nod = q.top().second;
        q.pop();

        if(viz[nod] == 0)
        {
            for(auto i : h[nod])
                if(i.second + cost < d[i.first])
                {
                    d[i.first] = i.second + cost;
                    q.push({d[i.first], i.first});
                }
            viz[nod] = 1;
        }

    }

}

int main()
{
    int x, y, z;
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y >> z;
        h[x].push_back({y, z});
     ///   h[y].push_back({x, z});
    }
    Dijkstra(1);
    for(int i = 2; i <= n; i++)
        if(d[i] == 1e9) fout << "-1 ";
        else fout << d[i] << " ";

    return 0;
}