Cod sursa(job #3296248)

Utilizator andrei.nNemtisor Andrei andrei.n Data 12 mai 2025 11:24:42
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>
#define int int64_t

using namespace std;

const int NMAX = 50005;
const int INF = 999999999;

struct Edge
{
    int n,c;
};

vector<Edge> v[NMAX];
int cost[NMAX];
int from[NMAX];
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;

void dijkstra(int source)
{
    pq.emplace(0, source);
    cost[source] = 0;
    while(!pq.empty())
    {
        int node = pq.top().second;
        int c = pq.top().first;
        pq.pop();
        if(cost[node] != c) continue;
        for(auto &oth : v[node])
            if(cost[oth.n] > c + oth.c)
            {
                cost[oth.n] = c + oth.c;
                from[oth.n] = node;
                pq.emplace(cost[oth.n], oth.n);
            }
    }
}

signed main()
{
    ifstream fin ("dijkstra.in");
    ofstream fout ("dijkstra.out");
    ios::sync_with_stdio(false); fin.tie(0); fout.tie(0);
    int n,m; fin>>n>>m;
    for(int i=0; i<m; ++i)
    {
        int x,y,c; fin>>x>>y>>c;
        v[x].push_back({y,c});
    }
    for(int i=1; i<=n; ++i)
        cost[i] = INF;
    dijkstra(1);
    for(int i=2; i<=n; ++i)
        fout<<(cost[i] == INF ? 0 : cost[i])<<' ';
    return 0;
}