Cod sursa(job #3214771)

Utilizator _andrei4567Stan Andrei _andrei4567 Data 14 martie 2024 13:49:34
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream cin ("dijkstra.in");
ofstream cout ("dijkstra.out");

const int INF = 1e9;
const int N = 5e4;
int dp[N + 1];

struct node
{
    int nod, cost;
    bool operator < (const node &a)const
    {
        return cost > a.cost;
    }
};

vector <node> g[N + 1];

priority_queue <node> pq;

int n, m, x, y, cost;

void dijkstra (int start)
{
    for (int i = 1; i <= n; ++i)
        dp[i] = INF;
    dp[start] = 0;
    pq.push({start, 0});
    while (!pq.empty())
    {
        node x = pq.top();
        pq.pop();
        if (x.cost > dp[x.nod])continue;
        for (auto it : g[x.nod])
            if (dp[x.nod] + it.cost < dp[it.nod])
                dp[it.nod] = dp[x.nod] + it.cost, pq.push({it.nod, dp[it.nod]});
    }
    for (int i = 2; i <= n; ++i)
        cout << dp[i] << ' ';
}

int main()
{
    cin >> n >> m;
    for (int i = 1; i <= m; ++i)
    {
        cin >> x >> y >> cost;
        g[x].push_back({y, cost});
    }
    dijkstra (1);
    return 0;
}