Cod sursa(job #3214138)

Utilizator SerbanCaroleSerban Carole SerbanCarole Data 13 martie 2024 20:32:35
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
using pii = pair<int,int>;
ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");
const int nmax = 1e5 + 1;
struct cmp
{
    bool operator()(pii a, pii b)
    {
        return a.second > b.second;
    }
};
priority_queue<pii,vector<pii>,cmp>pq;
vector <pii> g[nmax];
int n , m , x , y , c , dp[nmax];
signed main()
{
    cin >> n >> m;
    for(int i = 1 ; i <= n ; ++i) dp[i] = 1e9;
    dp[1] = 0;
    for(int i = 1 ; i <= m ; ++i)
    {
        cin >> x >> y >> c;
        g[x].push_back({y,c});
    }
    pq.push({1,0});
    while(!pq.empty())
    {
        pii aux = pq.top();
        pq.pop();
        x = aux.first;
        for(auto it : g[x])
        {
            if(dp[it.first] > dp[x] + it.second)
            {
                dp[it.first] = dp[x] + it.second;
                pq.push({it.first,dp[it.first]});
            }
        }
    }
    for(int i = 2 ; i <= n ; ++i) cout << dp[i] << ' ';
    return 0;
}