Cod sursa(job #3244720)

Utilizator FlaviuuuFlaviu Flaviuuu Data 26 septembrie 2024 10:26:14
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <fstream>
#include <map>
using namespace std;
ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");
int n, s, f[50000], d[50000];
int m;
map<pair<int, int>, int> a;
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;
}