Cod sursa(job #2175362)

Utilizator maenstru56Peteleaza Darius maenstru56 Data 16 martie 2018 16:51:54
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <iostream>
#include <fstream>
#include <climits>

using namespace std;

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

int n, m, c[15000][15000], d[50005], viz[50005], p[50005];

void citire(){
    in >> n >> m;

    int x, y, cost;

    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= n; j++){
            if(i == j)
                c[i][j] = 0;
            else
                c[i][j] = INT_MAX/2;
        }
    }

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

int val_min(){
    int mi = INT_MAX/2, poz;

    for(int i = 1; i <= n; i++){
        if(d[i] < mi && viz[i] == 0){
            mi = d[i];
            poz = i;
        }
    }

    return poz;
}

void Dijkstra(int x){
    viz[x] = 1;

    for(int i = 1; i <= n; i++){
        d[i] = c[x][i];

        if(d[i] != INT_MAX/2)
            p[i] = x;
    }

    for(int k = 1; k <= n-2; k++){
        int nod = val_min();
        viz[nod] = 1;

        for(int i = 1; i <= n; i++){
            if(viz[i] == 0 && c[nod][i] != INT_MAX/2 && (d[nod] + c[nod][i] < d[i])){
                d[i] = d[nod] + c[nod][i];
                p[i] = nod;
            }
        }
    }
}

void afis(int x, int y){
    if(x != y){
        afis(x, p[y]);
        cout << y << " ";
    }
    else
        cout << x << " ";
}

int main()
{
    citire();
    Dijkstra(1);

    for(int i = 2; i <= n; i++){
        if(d[i] != INT_MAX/2)
            out << d[i] << " ";
        else
            out << 0 << " ";
    }

    return 0;
}