Cod sursa(job #2228086)

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

using namespace std;

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

int n, m, d[50005];
vector < pair < int, int > > graph[50005];
bool inQ[50005];

struct comp
{
    bool operator()(int x, int y)
    {
        return d[x] > d[y];
    }
};
priority_queue <int, vector <int>, comp> Q;

int main()
{
    int x, y, c, k;

    fin >> n >> m;

    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y >> c;
        graph[x].push_back(make_pair(y,c));
    }

    for(int i = 2; i <= n; i++)
        d[i] = 1000000005;

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

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

        for(auto it : graph[cnd])
        {
            k = it.first;
            c = it.second;
            if(d[cnd] + c < d[k])
            {
                d[k] = d[cnd] + c;
                if(inQ[k] == false)
                {
                    Q.push(k);
                    inQ[k] = true;
                }
            }
        }
    }

    for(int i = 2; i <= n; i++)
        fout << ( (d[i] == 1000000005) ? 0 : d[i] ) << ' ';

    return 0;
}