Cod sursa(job #2203086)

Utilizator hertzalauPOPESCU ION hertzalau Data 10 mai 2018 21:11:58
Problema Algoritmul lui Dijkstra Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>

using namespace std;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
int n, m, mat[1005][1005], c[1000000], dist[1005], viz[1005];

int minimum(int c[], int viz[], int st, int dr)
{
    int M = 999999999, y, r;
    for(int i = st; i <= dr; i++)
    {
        if(dist[c[i]] < M && viz[i] == 0)
            M = dist[c[i]], y = c[i], r = i;
    }
    if(M == 999999999)
        return -1;
    viz[r] = 1;
    return y;
}
int main()
{
    in >> n >> m;
    for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) mat[i][j] = -1;
    for(int i= 1; i <= m; i++)
    {
        int x, y, z;
        in >> x >> y >> z;
        mat[x][y] = z;
    }
    c[1] = 1;
    int s = 0, ct = 1;
    for(int i = 1; i <= n; i++)
        dist[i] = 999999999;
    dist[1] = 0;
    int ok = 1;
    while(ok == 1)
    {

        ok = 0;
        int x = minimum(c, viz, 1, ct);
        if(x == -1)
            ok = 0;
        else {ok = 1;
        for(int i = 1; i <= n; i++)
            if(mat[x][i] != -1 && dist[x] + mat[x][i] < dist[i])
            {
                ct++;
                c[ct] = i;
                dist[i] = dist[x] + mat[x][i];
            }
    }}
    for(int i = 2; i <= n; i++)
        if(dist[i] != 999999999)
        out << dist[i] << " ";
    else out << 0 << " ";
    return 0;
}