Cod sursa(job #3236131)

Utilizator AndreiJJIordan Andrei AndreiJJ Data 26 iunie 2024 13:20:53
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <bits/stdc++.h>

using namespace std;


vector <pair <int, int> > L[50001];
int n, m, dist[50001];
priority_queue <pair<int, int>, vector <pair<int, int> >, greater<pair<int, int> > > pq; // first -> distanta de la nodul sursa, second o sa fie nodul cu distanta first


void Read()
{
    ifstream fin ("dijkstra.in");
    fin >> n >> m;
    while (m--)
    {
        int x, y, c;
        fin >> x >> y >> c;
        L[x].push_back({y, c});
    }
}

void Dijkstra()
{
    for (int i = 1; i <= n; i++)
        dist[i] = 2e9;
    dist[1] = 0;
    pq.push({0, 1});
    while (!pq.empty())
    {
        pair <int, int> curr = pq.top();
        pq.pop();
        if (dist[curr.second] < curr.first) continue;
        for (auto next : L[curr.second])
            if (dist[next.first] > curr.first + next.second)
            {
                dist[next.first] = curr.first + next.second;
                pq.push({dist[next.first], next.first});
            }
    }
    ofstream fout ("dijkstra.out");
    for (int i = 2; i <= n; i++)
        (dist[i] == 2e9) ? fout << "0 " : fout << dist[i] << " ";
}

int main()
{
    Read();
    Dijkstra();
    return 0;
}