Cod sursa(job #1980164)

Utilizator LittleWhoFeraru Mihail LittleWho Data 12 mai 2017 15:28:53
Problema Algoritmul lui Dijkstra Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <bits/stdc++.h>

#define INF (1 << 17)
#define MAX_N 50000

using namespace std;

typedef pair<int, int> intPair;
typedef vector< vector<int> > intMatrix;
typedef vector< vector<intPair> > intPairMatrix;

intPairMatrix graph(MAX_N);
vector<int> dist(MAX_N, INF);

int main()
{
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);

    int n, m;
    cin >> n >> m;

    for (int i = 0, from, to, cost; i < m; i++) {
        cin >> from >> to >> cost;
        graph[from - 1].push_back(make_pair(cost, to - 1));
    }

    priority_queue< intPair, vector<intPair>, greater<intPair> > min_heap;
    min_heap.push(make_pair(0, 0));
    dist[0] = 0;

    while (!min_heap.empty()) {
        intPair min_vertex = min_heap.top();
        min_heap.pop();

        int min_vertex_i = min_vertex.second;

        vector<intPair>::iterator it;
        for (it = graph[min_vertex_i].begin();
                it != graph[min_vertex_i].end();
                it++) {
            int cvertex_weight = (*it).first;
            int cvertex_i = (*it).second;
            int sum = dist[min_vertex_i] + cvertex_weight;

            if (dist[cvertex_i] > sum) {
                dist[cvertex_i] = sum;
                min_heap.push((*it));
            }
        }
    }

    for (int i = 1; i < n; i++) {
        if (dist[i] == INF)
            dist[i] = 0;
        cout << dist[i] << " ";
    }
    cout << "\n";

    return 0;
}