Cod sursa(job #2924488)

Utilizator Vincent47David Malutan Vincent47 Data 3 octombrie 2022 16:42:16
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <fstream>

using namespace std;
ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");
const int inf = 0x3f3f3f3f;
int c[101][101], d[101], n, m;
bool s[101];

    void djk(int x, int d[]) {
        s[x] = 1;
        for (int i = 1; i <= n; ++i)
            d[i] = c[x][i];
        for (int pas = 1; pas < n; ++pas) {
           int dmin = inf;
           for (int y = 1; y <= n; ++y)
           {
               if (!s[y] && d[y] < dmin) {
                dmin = d[y];
                x = y;
               }
               s[x] = 1;
               for (int y = 1; y <= n; ++y)
                if (d[y] > d[x] + c[x][y])
                d[y] = d[x] + c[x][y];

           }
        }
    }

int main()
{
    cin >> n >> m;
int x, y, w;
    for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= n; ++j)
            if (i != j)
        c[i][j] = inf;

    for (int i = 1; i <= m; ++i) {
        cin >> x >> y >> w;
        c[x][y] = w;
    }

    djk(1, d);
    for (int i = 2; i <= n; ++i)
        if (d[i] == inf)
        cout << '0' << ' ';
    else
        cout << d[i] << ' ';
    return 0;
}