Cod sursa(job #2803794)

Utilizator andreimocianAndrei Mocian andreimocian Data 20 noiembrie 2021 14:17:06
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

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

int n, m;
int dp[50005];
vector < el > L[50005];
priority_queue < el > Q;

void citire()
{
    int x, y, z;
    el w;
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y >> z;
        w.node = y;
        w.cost = z;
        L[x].push_back(w);
    }
}

void dijkstra()
{
    for(int i = 2; i <= n; i++)
    {
        dp[i] = 1e9;
    }
    el w2;
    w2.node = 1;
    w2.cost = 0;
    Q.push(w2);
    while(!Q.empty())
    {
        el w = Q.top();
        Q.pop();
        for(auto it : L[w.node])
        {
            if(dp[it.node] > dp[w.node] + it.cost)
            {
                dp[it.node] = dp[w.node] + it.cost;
                w2.node = it.node;
                w2.cost = dp[it.node];
                Q.push(w2);
            }
        }
    }
}

int main()
{
    citire();
    dijkstra();
    for(int i = 2; i <= n; i++)
    {
        if(dp[i] == 1e9)
            fout << 0 << " ";
        else
            fout << dp[i] << " ";
    }
    return 0;
}