Cod sursa(job #3323435)

Utilizator _irina__irina tanase _irina__ Data 18 noiembrie 2025 12:50:13
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <bits/stdc++.h>
#include <queue>
#include <fstream>
using namespace std;

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

int inf = 1e9;



void dijkstra()
{
    int n, m;

    fin >> n >> m;

    priority_queue<pair<int, int>> pq;

    vector<long long> dist(n + 1, inf);
    vector<pair<int, int>> L[n + 1];
    vector<int> vis(n + 1, 0);

    for(int i = 1; i <= m; i ++)
    {
        int x, y, ct;

        fin >> x >> y >> ct;

        L[x].push_back({y, ct});
        //L[y].push_back({x, -ct});
    }

    dist[1] = 0;

    pq.push({-dist[1], 1});

    while(!pq.empty())
    {
        int node = pq.top().second;
        pq.pop();
        
        if(vis[node] != 1)
        {
            vis[node] = 1;
            for(auto elem: L[node])
            {
                int vecin = elem.first;
                int cost = elem.second;

                if(dist[vecin] > dist[node] + cost)
                {
                    dist[vecin] = dist[node] + cost;
                    pq.push({-dist[vecin], vecin});
                }
            }
        }
    }

    for(int d = 2; d <= n; d++)
    {
        if(vis[d] == 0) dist[d] = 0;
        
        fout << dist[d] << ' ';
    }


}

int main()
{
    dijkstra();
    return 0;
}