Cod sursa(job #2046717)

Utilizator radu.leonardoThe Doctor radu.leonardo Data 24 octombrie 2017 01:26:27
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>

 

using namespace std;

ifstream f("dijkstra.in");

ofstream g("dijkstra.out");

 

int N, M;

int D[50001];

vector<pair<int, int>> G[50001];

priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> PQ;

 

void Read() {

    f >> N >> M;

    for (int i = 1; i <= M; i++) {

        int x, y, c;

        f >> x >> y >> c;

        G[x].push_back({c, y});

        G[y].push_back({c, x});

    }

}

 

void Dijkstra() {

    D[1] = 0;

    for (int i = 2; i <= N; i++) D[i] = -1;

    for (auto it:G[1])

        PQ.push(it),

                D[it.second] = it.first;

 

    while (!PQ.empty()) {

        pair<int, int> current = PQ.top();

        PQ.pop();

        for (auto next:G[current.second])

            if (D[next.second]==-1 && D[next.second] > D[current.second] + next.first)

                D[next.second] = D[current.second] + next.first,

                        PQ.push(next);

    }

 

    for (int i = 2; i <= N; i++)

        if (D[i] == INT_MAX) g << "0 ";

        else g << D[i] << ' ';

}

 

int main() {

    Read();

    Dijkstra();

}