Cod sursa(job #2087712)

Utilizator Teodor.mTeodor Marchitan Teodor.m Data 14 decembrie 2017 01:21:15
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("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);
    viz[1] = true;

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

        for(const 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;
    fin >> n >> m;

    for(int i = 1; i <= m; ++i) {
        int a, b, c;
        fin >> 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)
            fout << "0 ";
        else
            fout << dist[i] << " ";
    }

    return 0;
}