Cod sursa(job #3266819)

Utilizator iccjocIoan CHELARU iccjoc Data 10 ianuarie 2025 16:40:40
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>
using namespace std;
vector<int> dijkstra(int n, int source, vector<vector<pair<int, int>>> graph)
{
    priority_queue<pair<int, int>> p;
    const int INF = 2e9;
    vector<int> dist(n + 1, INF);
    p.push({-0, source});
    dist[source] = 0;
    while(!p.empty())
    {
        int c = -p.top().first;
        int k = p.top().second;
        p.pop();
        if(c != dist[k])
            continue;
        for(auto it = graph[k].begin(); it != graph[k].end(); it++)
        {
            if(dist[(*it).first] > dist[k] + (*it).second)
            {
                dist[(*it).first] = dist[k] + (*it).second;
                p.push({-dist[(*it).first], (*it).first});
            }
        }
    }
    return dist;
}
int main()
{
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);
    int n, m;
    cin >> n >> m;
    vector<vector<pair<int, int>>> graph(n + 5);
    for(int i = 0; i < m; i++)
    {
        int x, y, c;
        cin >> x >> y >> c;
        graph[x].push_back({y, c});
    }
    vector<int> dist;
    dist = dijkstra(n, 1, graph);
    for(auto it = dist.begin() + 2; it != dist.end(); it++)
    {
        cout << (*it) << " ";
    }
}