Cod sursa(job #2766547)

Utilizator pielevladutPiele Vladut Stefan pielevladut Data 2 august 2021 11:28:46
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>

using namespace std;

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

int t;
int n, m, s;
int d[50505];
int ans[50505];
struct elem
{
    int nod, cost;
    bool operator < (const elem other) const
    {
        return cost > other.cost;
    }
};
vector<elem> v[50505];
priority_queue<elem> coada;
void Dijkstra(int nod)
{
    coada.push({nod, 0});
    while(!coada.empty())
    {
        int nod = coada.top().nod;
        int cost = coada.top().cost;
        coada.pop();
        if(cost != ans[nod])
            continue;
        for(auto it : v[nod])
        {
            if(cost + it.cost < ans[it.nod])
            {
                ans[it.nod] = cost + it.cost;
                coada.push({it.nod, ans[it.nod]});
            }
        }
    }
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= n; i ++)
    {
        ans[i] = INT_MAX;
    }
    s = 1;
    ans[s] = 0;
    while(m--)
    {
        int a, b, c;
        fin >> a >> b >> c;
        v[a].push_back({b,c});
    }
    Dijkstra(s);
    bool ok = true;
    for(int i = 2; i <= n; i ++)
    {
        if(ans[i] == INT_MAX)
            ans[i] = 0;
        fout << ans[i] << ' ';
    }
}