Cod sursa(job #1988728)

Utilizator Emy1337Micu Emerson Emy1337 Data 4 iunie 2017 14:30:01
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <algorithm>

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

const int MAXN = 50010;
const int inf = (1 << 31) - 1;

struct comp
{
    bool operator () (const pair<int, int> a, const pair<int, int> b)
    {
        return a.first > b.first;
    }
};



priority_queue< pair<int, int>, vector<pair<int, int> >, comp> heap;
vector<pair<int, int> >graph[MAXN];

int n, m, dist[MAXN];

void dijkstra()
{

    fill(dist, dist + n + 1, inf);

    heap.push(make_pair(0, 1));
    dist[1] = 0;

    while (!heap.empty())
    {
        int nod = heap.top().second;
        heap.pop();

        for (auto it : graph[nod])
        {
            if (dist[it.first] > dist[nod] + it.second)
            {
                dist[it.first] = dist[nod] + it.second;
                heap.push(make_pair(dist[it.first], it.first));
            }
        }
    }
}

int main()
{
    fin >> n >> m;

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

    dijkstra();

    for (int i = 2; i <= n; ++i)
        fout << (dist[i] == inf ? 0 : dist[i] )<< " ";



    return 0;

}