Cod sursa(job #2196596)

Utilizator EclipseTepes Alexandru Eclipse Data 19 aprilie 2018 19:42:54
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <fstream>
#include <vector>
#define dMAX 50000
#define INF 999999

using namespace std;

int n, m, x, y, c;
vector<pair<int, int> > graf[dMAX + 2];
pair<int, int> pVerif;
bool viz[dMAX + 2];
int topSort[dMAX + 2];
int d[dMAX + 2];

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

void DFS(int v) {
    viz[v] = true;
    int newV, u;
    for (u = 0; u < graf[v].size(); u++) {
        newV = graf[v][u].first;
        if (!viz[newV]) {
            DFS(newV);
        }
    }
    topSort[++topSort[0]] = v;
}

int main()
{
    int i, j, newV;
    fin >> n >> m;
    for (i = 1; i <= m; i++) {
        fin >> x >> y >> c;
        graf[x].push_back({y, c});
    }

    DFS(1);

    for (i = 1; i <= n; i++) d[i] = INF;
    d[1] = 0;

    for (i = n; i >= 1; i--) {
        for (j = 0; j < graf[topSort[i]].size(); j++) {
            if (d[graf[topSort[i]][j].first] > d[topSort[i]] + graf[topSort[i]][j].second) {
                d[graf[topSort[i]][j].first] = d[topSort[i]] + graf[topSort[i]][j].second;
            }
        }
    }

    for (i = 2; i <= n; i++) fout << d[i] << ' ';

    return 0;
}