Cod sursa(job #2758966)

Utilizator pokermon2005paun darius alexandru pokermon2005 Data 14 iunie 2021 18:00:24
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

const int N = 50001;
const int INF = 1e9 + 100;

vector < pair <int, int>> a[N];
priority_queue < pair <int, int>> pq;
int d[N], n, m;
bool prelucrat[N];

void dijkstra(int x0)
{
    //initializez d
    for (int i = 1; i <= n; i++)
    {
        d[i] = INF;
    }
    d[x0] = 0;
    pq.push({-d[x0], x0});
    while (!pq.empty())
    {
        int x = pq.top().second;
        pq.pop();
        if (prelucrat[x])
        {
            continue;
        }
        prelucrat[x] = true;
        //actualizam distantele fata de succesorii lui x
        for (auto p: a[x])
        {
            int y = p.first;
            int c = p.second;
            if (d[x] + c < d[y])
            {
                d[y] = d[x] + c;
                pq.push({-d[y], y});
            }
        }
    }
}

int main()
{
    ifstream in("dijkstra.in");
    ofstream out("dijkstra.out");
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y, c;
        in >> x >> y >> c;
        a[x].push_back({y, c});
    }
    dijkstra(1);
    for (int i = 2; i <= n; i++)
    {
        if (d[i] == INF)
        {
            d[i] = 0;
        }
        out << d[i] << " ";
    }
    out.close();
    return 0;
}