Cod sursa(job #2807454)

Utilizator AndreeaCreitaCreita Andreea AndreeaCreita Data 23 noiembrie 2021 20:18:40
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <iostream>
#include <bits/stdc++.h>

using namespace std;

ifstream f ("dijkstra.in");
ofstream g ("dijkstra.out");

const int INF = 1e9;

vector<pair<int,int>> la[50005];
int dist[50005];
int n,m;

void dijkstra(int s)
{
    dist[s] = 0;
    queue<pair<int,int>> pq;
    pq.push({0, s});

    while (pq.size())
    {
        int from = pq.front().second;
        pq.pop();
        for (auto& per: la[from])
        {
            int to = per.first;
            int cost = per.second;

            if (dist[to] > dist[from] + cost)
            {
                dist[to] = dist[from] + cost;
                pq.push({-cost, to});
            }
        }
    }
}

int main()
{
    f >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x,y,d;
        f >> x >> y >> d;
        la[x].push_back({y,d});
    }

    for (int i = 1; i <= n; i++)
        dist[i] = INF;

    dijkstra(1);

    for (int i = 2; i <= n; i++)
    {
        if (INF == dist[i])
            dist[i] = 0;
        g << dist[i] << ' ';
    }

    return 0;
}