Cod sursa(job #3244718)

Utilizator FlaviuuuFlaviu Flaviuuu Data 26 septembrie 2024 10:20:34
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
using namespace std;
ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");
int n, s, f[105], a[105][105], d[105];
int m;
int main()
{
    cin>>n>>m;
    s = 1;
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++)
            a[i][j] = 1e9;
    int x, y, z;
    for(int i = 1; i <= m; i++)
        cin>>x>>y>>z, a[x][y] = z;
    for(int i = 1; i <= n; i++)
        d[i] = a[s][i];
    f[s] = 1;
    d[s] = 0;
    d[0] = 1e9;
    for(int k = 1; k < n; k++)
    {
        int pmax = 0;
        for(int i = 1; i <= n; i++)
            if(f[i] == 0 && d[i] < d[pmax])
                pmax = i;
        if(pmax != 0)
        {
            f[pmax] = 1;
            for(int i = 1; i <= n; i++)
                if(f[i] == 0 && d[pmax] + a[pmax][i] < d[i])
                    d[i] = d[pmax] + a[pmax][i];
        }
    }
    for(int i = 2; i <= n; i++)
    {
        if(d[i] == 1e9)
            cout<<"0"<<" ";
        else
            cout<<d[i]<<" ";
    }
    return 0;
}