Cod sursa(job #2196597)

Utilizator EclipseTepes Alexandru Eclipse Data 19 aprilie 2018 19:44:28
Problema Algoritmul lui Dijkstra Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 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++) {
        if (d[i] != INF) fout << d[i] << ' ';
        else fout << 0 << ' ';
    }

    return 0;
}