Cod sursa(job #1881281)

Utilizator saba_alexSabadus Alex saba_alex Data 16 februarie 2017 12:34:10
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int MAX = 50005;
const int inf = (1 << 31) - 1;
vector < pair < int, int> > G[MAX];
priority_queue < pair < int, int > > PQ;
int dist[MAX], viz[MAX];
int n, m, x, y, z, nod;

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= m; ++i){
        fin >> x >> y >> z;
        G[x].push_back( make_pair(y, z) );
    }

    dist[1] = 0;
    for(int i = 2; i <= n; ++i)
        dist[i] = inf;
    PQ.push( make_pair(0, 1) );

    ///dijkstra
    while(!PQ.empty()){
        pair < int, int > aux = PQ.top();
        PQ.pop();
        nod = aux.second;
        if(viz[nod])
            continue;
        viz[nod] = 1;
        for(auto it: G[nod]){
            if(dist[nod] + it.second < dist[it.first]){
                dist[it.first] = dist[nod] + it.second;
                PQ.push( make_pair( -dist[it.first], it.first) );
            }
        }
    }

    for(int i = 2; i <= n; ++i){
        if(dist[i] == inf)
            dist[i] = 0;
        fout << dist[i] << ' ';
    }

    return 0;
}