Cod sursa(job #2870416)

Utilizator AndreiP25Prusacov Andrei AndreiP25 Data 12 martie 2022 12:30:33
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>
using namespace std;

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

#define INF (1<<31)-1

vector <pair<int,int>>A[50001];
priority_queue<pair<int,int>>Q;
int dist[50001],n,m, parent[50001],q;

void dijkstra()
{
    for(int i=1; i<=n;i++)
    {
        dist[i]=INF;
        parent[i]=0;
    }
    dist[1]=0;
    Q.push({0,1});
    while(!Q.empty())
    {
        int a=Q.top().second;
        Q.pop();
        for(auto u:A[a])
        {
            int b=u.first;
            int c=u.second;
            if(dist[b]>dist[a]+c)
            {
                dist[b]=dist[a]+c;
                parent[b]=a;
            }
            Q.push({-dist[b],b});
        }
    }
}

void path(int n)
{
    if(parent[n]==0)
    {
        cout<<1<<" ";
        return;
    }
    path(parent[n]);
    cout<<n<<" ";
}

int main()
{
    fin>>n>>m;
    for(int i=1; i<=m; i++)
    {
        int a,b,p;
        fin>>a>>b>>p;
        A[a].push_back({b,p});
    }

    dijkstra();
    for(int i=2; i<=n; i++)
        if(dist[i]!=INF)
            fout<<dist[i]<<" ";
        else
            fout<<0<<" ";
    //path(5);
    return 0;
}