Cod sursa(job #3030786)

Utilizator AndreiCroitoruAndrei Croitoru AndreiCroitoru Data 17 martie 2023 21:15:01
Problema Algoritmul lui Dijkstra Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>

using namespace std;

const int N = 50'001;
vector <pair<int, int> > g[N];
int dist[N];
bool verif[N];
void dijkstra(int node)
{
    priority_queue <pair<int, int>> pq;
    pq.push({0, node});
    while(!pq.empty())
    {
        pair<int, int> aux = pq.top();
        if(!verif[aux.second])
        {
            verif[aux.second] = 1;
            for(auto next : g[aux.second])
            {
                if(dist[next.second] > dist[aux.second] + next.first)
                {
                    dist[next.second] = dist[aux.second] + next.first;
                    pq.push({-dist[next.second], next.second});
                }
            }
        }
        pq.pop();
    }
}
int main()
{
    ifstream cin("dijkstra.in");
    ofstream cout("dijkstra.out");

    int n, m;
    cin >> n >> m;
    for(int i = 1; i <= m; i ++)
    {
        int a, b ,c;
        cin >> a >> b >> c;
        g[a].push_back({c, b});
    }
    for(int i = 2; i <= n; i ++)
    {
        dist[i] = INT_MAX;
    }
    dijkstra(1);
    for(int i = 2; i <= n; i ++)
    {
        if(dist[i] != INT_MAX)
            cout << dist[i] << " ";
        else
            cout << "0 ";
    }
    return 0;
}