Cod sursa(job #2750823)

Utilizator PatrascuAdrian1Patrascu Adrian Octavian PatrascuAdrian1 Data 13 mai 2021 12:41:15
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <bits/stdc++.h>

using namespace std;

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

const int Nmax = 50001, INF = 1e9 + 1;
vector<pair<int,int>> G[Nmax];
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> Q;
int N, M, x, y, c;
int dp[Nmax];
bool seen[Nmax];

void dijkstra(int v)
{
    Q.push({0,v});
    dp[v] = 0;
    while(!Q.empty())
    {
        while(!Q.empty() && seen[Q.top().second])
            Q.pop();
        if(!Q.empty())
        {
            int u = Q.top().second;
            seen[u] = 1;
            Q.pop();
            for(auto i : G[u])
            {
                int nod = i.first;
                int cost_nod = i.second;
                if(dp[nod] > dp[u] + cost_nod)
                {
                    dp[nod] = dp[u] + cost_nod;
                    Q.push({dp[nod], nod});
                }
            }

        }
    }
}

int main()
{
    ios_base::sync_with_stdio(0);
    in >> N >> M;
    while(M--)
    {
        in >> x >> y >> c;
        G[x].push_back({y,c});
    }
    for(int i = 1; i <= N; ++i)
        dp[i] = INF;
    dijkstra(1);
    for(int i = 2; i <= N; ++i)
        out << (dp[i] == INF ? 0 : dp[i]) << " ";
    return 0;
}