Cod sursa(job #2113088)

Utilizator ioanadarcCristina Arc ioanadarc Data 24 ianuarie 2018 11:15:11
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define Nmax 50005
#define INF 1 << 30
using namespace std;

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

int dp[Nmax], x, y, c, N, M;
struct str
{
   int nod, cost;
   bool operator < (const str &other) const{
       return cost > other.cost;
   }
};
priority_queue<str>pq;
vector<pair<int,int>>g[Nmax];
void dijkstra()
{
    dp[1] = 0;
    pq.push({1, 0});
    while(!pq.empty())
    {
        int nd = pq.top().nod;
        int cst = pq.top().cost;
        pq.pop();
        if(dp[nd] != cst)continue;
        for(int i = 0 ; i < g[nd].size(); i++)
        {
            int next = g[nd][i].first;
            if(dp[nd] + g[nd][i].second < dp[next])
            {
                dp[next] = dp[nd] + g[nd][i].second;
                pq.push({next, dp[next]});
            }
        }
    }
}
int main()
{
    fin >> N >> M;
    for(int i = 1; i <= M; i++)
    {
        fin >> x >> y >> c;
        g[x].push_back({y, c});
    }
    for(int i = 1; i <= N; i++)
        dp[i] = INF;
    dijkstra();
    for(int i = 2; i <= N; i++)
        fout << dp[i] << " ";
    return 0;
}