Cod sursa(job #3246285)

Utilizator Ruxandra009Ruxandra Vasilescu Ruxandra009 Data 2 octombrie 2024 16:59:48
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <fstream>
#include <climits>
#include <vector>
#include <queue>

using namespace std;

const int nmax = 50005;
const int inf = INT_MAX;

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

struct ceva{
    int vec, cost;
};

int n, m, fr[nmax], a[nmax];
vector<ceva> v[nmax];
priority_queue< pair<int, int> > H;

void dijk(int nod)
{
    a[nod] = 0; H.push(make_pair(0, nod));
    for(int i = 1; i <= n; i ++)
    {
        while(!H.empty() && fr[H.top().second])
            H.pop();
            
        int poz = H.top().second;
        fr[poz] = 1;

        for(auto x : v[poz])
            if(a[x.vec] > x.cost + a[poz])
                a[x.vec] = x.cost + a[poz], H.push(make_pair(a[x.vec], x.vec));
    }
}

int main()
{
    f >> n >> m;
    for(int i = 1; i <= m; i ++)
    {
        int x, y, c;
        f >> x >> y >> c;
        v[x].push_back({y, c});
    }

    for(int i = 1; i <= n; i ++)
        a[i] = inf;

    dijk(1);

    for(int i = 2; i <= n; i ++)
        if(a[i] != inf)
            g << a[i] << " ";
        else
            g << 0 << " ";
    return 0;
}