Cod sursa(job #2151847)

Utilizator ade_tomiEnache Adelina ade_tomi Data 4 martie 2018 23:02:44
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstdio>

using namespace std;

const int NMAX = 50004, INF = 0x3f3f3f3f;

vector < pair<int, int> > v[NMAX];
priority_queue < pair <int, int> > q; 

int d[NMAX];

void dijkstra(int start) {
    q.push(make_pair(0, start));
    d[start] = 0;

    while (!q.empty()) {
        int nod = q.top().second;

        q.pop();

        for (int i = 0; i < v[nod].size(); i++) {
            int dest = v[nod][i].first;
            int c = v[nod][i].second;

            if (d[nod] + c < d[dest]) {
                d[dest] = d[nod] + c;
                q.push(make_pair(-d[dest], dest));
            }
        }
    }
}

int main() {
    int n, m, a, b, c;

    ifstream cin  ("dijkstra.in");
    ofstream cout ("dijkstra.out");

    cin >> n >> m; 

    for (int i = 0; i < m; i++) { 
        cin >> a >> b >> c;

        v[a].push_back(make_pair(b, c));
    }

    memset(d, INF, sizeof(d));

    dijkstra(1);

    for (int i = 2; i <= n; i++) {
        if (d[i] == INF) {
            cout << "0 ";
        } else {
            cout << d[i] << " ";
        }
    }

    return 0;
}