Cod sursa(job #2370954)

Utilizator FredyBobi Rusu Fredy Data 6 martie 2019 14:46:50
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

#define limn 50010
#define inf 2e9
int n,m;
vector <pair <int, int>> G[limn];
priority_queue <pair <int, int>> q;
int path[limn];

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

    }
}

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

    dijkstra(1);
    for(int i=2; i<=n; i++)
        fout<<path[i]<<' ';

    fin.close();
    fout.close();
    return 0;
}