Cod sursa(job #2417021)

Utilizator carreraPaul Achim carrera Data 28 aprilie 2019 18:56:51
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>
#define pii pair<int, int>
#define x first
#define y second

using namespace std;

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

const int INF = 0x3f3f3f3f;
const int N_MAX = 50000 + 5;

int n, m;
vector<pii> vec[N_MAX];
int cost[N_MAX];
priority_queue<pii, vector<pii>, greater<pii> > q;


int main()
{
    fin >> n >> m;
    while(m--){
        int aa, bb, cc;
        fin >> aa >> bb >> cc;
        vec[aa].push_back({bb,cc});
        vec[bb].push_back({aa,cc});
    }

    for(int i = 2; i <=n; ++i)
        cost[i] = INF;

    q.push({0, 1});
    while(!q.empty()){
        int nod = q.top().y;
        int cst = q.top().x;
        q.pop();

        if(cost[nod] != cst)
            continue;

        for(auto v : vec[nod]){
            int new_nod = v.x;
            int add_cost = v.y;

            if(cost[new_nod] > cst + add_cost){
                cost[new_nod] = cst + add_cost;
                q.push({cost[new_nod], new_nod});
            }
        }
    }

    for(int i = 2; i <=n; ++i)
        if(cost[i] > INF)
            fout << "0 ";
        else
            fout << cost[i] << " ";


    return 0;
}