Cod sursa(job #2228036)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 2 august 2018 15:58:33
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <fstream>
#include <vector>
#include <queue>
#define inf 1000000005
#define N 50005

using namespace std;

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

int nodes, edges, dist[N];
vector < pair < int, int > > graph[N];

struct compare
{
    bool operator()(int X, int Y)
    {
        return dist[X] < dist[Y];
    }
};

priority_queue < int, vector < int >, compare > Q;
bool inQ[N];

int main()
{
    int from, to, cost;

    fin >> nodes >> edges;

    for(int i = 1; i <= edges; i++)
    {
        fin >> from >> to >> cost;
        graph[from].push_back(make_pair(to,cost));
    }

    for(int i = 1; i <= nodes; i++)
        dist[i] = inf;

    dist[1] = 0;
    Q.push(1);
    inQ[1] = true;

    while(!Q.empty())
    {
        int currentNode = Q.top();
        Q.pop();
        inQ[currentNode] = false;

        for(auto it : graph[currentNode])
        {
            int child = it.first;
            int cost = it.second;
            if(dist[currentNode] + cost < dist[child])
            {
                dist[child] = dist[currentNode] + cost;
                if(inQ[child] == false)
                {
                    Q.push(child);
                    inQ[child] = true;
                }
            }
        }
    }

    for(int i = 2; i <= nodes; i++)
        fout << dist[i] << ' ';

    return 0;
}