Cod sursa(job #3343501)

Utilizator gabi_vag742Vasile Alexandru Gabriel gabi_vag742 Data 27 februarie 2026 17:04:23
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <bits/stdc++.h>
using namespace std;

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

const long long inf = LLONG_MAX;
int n, m;
vector<vector<pair<int,long long>>> graf;
vector<long long> cost(50005, inf);
priority_queue<pair<long long,int>> q;
vector<int> viz(50005);

void citire()
{
    fin >> n >> m;
    graf.resize(n+1);
    cost.resize(n+1);
    viz.resize(n+1);

    for(int i = 1; i <= m; i++)
    {
        int a, b, c;
        fin >> a >> b >> c;
        graf[a].emplace_back(b,c);
    }
}

void algoritm()
{
    q.push({0,1});

    while(!q.empty())
    {
        int nod = q.top().second;
        long long dist = q.top().first;
        q.pop();

        if(viz[nod] == 1)
            continue;
        viz[nod] = 1;

        for(auto next : graf[nod]) // next1 = nodul       next2 = costul muchiei A-B
        {
            if(-dist + next.second < cost[next.first])
            {
                cost[next.first] = -dist + next.second;
                q.push({-cost[next.first], next.first});
            }
        }
    }
}

void afisare()
{
    for(int i = 2; i <= n; i++)
        if(cost[i] == inf)
            fout << 0 << ' ';
        else
            fout << cost[i] << ' ';
}

int main ()
{
    citire();

    algoritm();

    afisare();

    return 0;
}