Cod sursa(job #2087708)

Utilizator Teodor.mTeodor Marchitan Teodor.m Data 14 decembrie 2017 00:38:03
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>
using namespace std;

fstream in("dijkstra.in");
ofstream out("dijkstra.out");

const int Nmax = 5e4 + 50;

vector< pair< int, int > > G[Nmax];
int dist[Nmax];
bool viz[Nmax];

struct cmp{
    bool operator() (int a, int b){
        return dist[a] > dist[b];
    }
};

void Dijkstra()
{
    priority_queue< int, vector< int >, cmp > pq;
    pq.push(1);

    while(!pq.empty()) {
        int node = pq.top(); pq.pop();
        viz[node] = false;

        for(auto it: G[node]) {
            if(dist[node] + it.second < dist[it.first]) {
                dist[it.first] = dist[node] + it.second;

                if(viz[it.first] == false) {
                    pq.push(it.first);
                    viz[it.first] = true;
                }
            }
        }
    }
}

int main()
{

    int n, m;
    in >> n >> m;

    for(int i = 1; i <= m; ++i) {
        int a, b, c;
        in >> a >> b >> c;

        G[a].push_back({b, c});
    }

    for(int i = 2; i <= n; ++i) dist[i] = INT_MAX;

    Dijkstra();

    for(int i = 2; i <= n; ++i) {
        if(dist[i] == INT_MAX)
            out << "0 ";
        else
            out << dist[i] << " ";
    }

    return 0;
}