Cod sursa(job #2828819)

Utilizator robertanechita1Roberta Nechita robertanechita1 Data 8 ianuarie 2022 00:10:10
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 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> >q;
int n, m, viz[100005], p;
int d[100005];

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

        if(cost > d[nod])
            continue;

        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});
            }
    }

}

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});
    }
    Dijkstra(1);
    for(int i = 2; i <= n; i++)
        if(d[i] == 2e9) fout << "-1 ";
        else fout << d[i] << " ";

    return 0;
}