Cod sursa(job #2665688)

Utilizator Pop_Rares123Pop Rares Pop_Rares123 Data 31 octombrie 2020 11:14:17
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <bits/stdc++.h>
#define limn 50010
#define inf 2e9

using namespace std;

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

int n,m,x,y,c;
int path[limn];
vector <pair <int,int> > G[limn];
priority_queue <pair <int,int> > pq;

void input()
{
    fin>>n>>m;
    while(m--)
    {
        fin>>x>>y>>c;
        G[x].push_back({y,c});
    }
}

void output()
{
    for(int i=2;i<=n;i++)
        if(path[i] == inf)

            fout<<0<<" ";

        else

            fout<<path[i]<<" ";
}

void dijkstra(int source)
{
    int cost,node;
    for(int i=2;i<=n;i++)
        path[i]=inf;
    path[source]=0;
    pq.push({0, source});
    while(!pq.empty())
    {
        node = pq.top().second;
        cost = -pq.top().first;
        pq.pop();
        if(path[node] != inf && path[node] != 0)
            continue;
        path[node] = cost;
        for(auto it:G[node])
            if(path[it.first] > cost + it.second)
                pq.push({-(cost+it.second), it.first});

    }
}

int main()
{
    input();
    dijkstra(1);
    output();
    return 0;
}