Cod sursa(job #2907020)

Utilizator Eduard_mihaiUngureanu Eduard Mihai Eduard_mihai Data 28 mai 2022 14:30:40
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>

using namespace std;

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

vector<pair<int, int>>a[50001];
int n,m,c[50001],d[50001];
priority_queue<pair<int, int>,vector<pair<int, int>>,greater<pair<int, int>>>q;

void citire(){
    cin>>n>>m;
    int x,y,c;
    for (int i=1; i<=m; i++){
        cin>>x>>y>>c;
        a[x].push_back(make_pair(y, c));
    }
}

void initializare(int nod)
{
    for (int i=1; i<=n; i++) d[i]=1e9;
    d[nod]=0;
}

void afisare(int nod){
    for (int i=1; i<=n; i++){
        if (i!=nod){
            if (d[i]==1e9) d[i]=0;
            cout<<d[i]<<" ";
        }
    }
}

void dijkstra(int nod)
{
    d[nod]=0;
    c[nod]=1;
    q.push(make_pair(d[nod], nod));
    while (!q.empty()){
        int x=q.top().second;
        q.pop();
        c[x]=0;
        for (auto p : a[x])
        {
            if (d[x]+p.second<d[p.first])
            {
                d[p.first]=d[x]+p.second;
                if (c[p.first]==0)
                {
                    q.push(make_pair(d[p.first], p.first));
                    c[p.first]=1;
                }
            }
        }
    }
}

int main()
{
    citire();
    initializare(1);
    dijkstra(1);
    afisare(1);
}