Cod sursa(job #2228069)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 2 august 2018 16:39:25
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

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


int n, m, dist[50005];
bool inQ[50005];

vector < pair < int, int > > graph[50005];

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

priority_queue< int, vector < int >, compare > Q;

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

    fin >> n >> m;

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

    for(int i = 1; i <= n; i++)
        dist[i] = 1000000005;

    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])
        {
            child = it.first;
            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 <= n; i++)
        if(dist[i] != 1000000005)
            fout << dist[i] << " ";
        else
            fout << "0 ";

    return 0;
}