Cod sursa(job #3319499)

Utilizator ZsomborZsombor Horvay Zsombor Data 1 noiembrie 2025 17:11:04
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <fstream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

const int inf = INT_MAX / 2;

ifstream be("dijkstra.in");
ofstream ki("dijkstra.out");

int main()
{
    int n, m;
    be >> n >> m;

    vector<vector<pair<int, int>>> adj(n + 1);

    int a, b, c;
    for(int i = 0; i < m; i++)
    {
        be >> a >> b >> c;
        adj[a].push_back({b, c});
    }

    vector<int> dist(n + 1, inf);
    dist[1] = 0;

    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
    q.push({dist[1], 1});

    while(!q.empty())
    {
        int cost_from = q.top().first;
        int from = q.top().second;
        q.pop();

        if(dist[from] == cost_from)
        {
            for(auto i : adj[from])
            {
                int to = i.first;
                int cost_to = i.second;
                
                if(dist[to] > dist[from] + cost_to)
                {
                    dist[to] = dist[from] + cost_to;

                    q.push({dist[to], to});
                }
            }
        }
    }

    for (int i = 2; i <= n; i++)
    {
        if (dist[i] == inf)
        {
            ki << 0 << " ";
        }else
        {
            ki << dist[i] << " ";
        }
    }

    return 0;
}