Cod sursa(job #2329565)

Utilizator netfreeAndrei Muntean netfree Data 26 ianuarie 2019 22:40:47
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 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 N_MAX = 50000 + 5;
const int INF = 0x3f3f3f3f;

int costs[N_MAX];
vector<pii> vec[N_MAX];
priority_queue<pii, vector<pii>, greater<pii> > q;

int n, m;

int main()
{
    fin >> n >> m;
    while(m--){
        int a, b, c;
        fin >> a >> b >> c;
        vec[a].push_back({b,c});
        vec[b].push_back({a,c});
    }

    for(int i = 1; i<=n; ++i)
        costs[i] = INF;

    costs[1] = 0;
    q.push({0,1});

    while(!q.empty()){
        int cost = q.top().x;
        int node = q.top().y;
        q.pop();

        if(cost != costs[node])
            continue;

        for(auto v : vec[node]){
            int dist = v.y;
            int vecNode = v.x;
            if(costs[vecNode] > costs[node] + dist){
                costs[vecNode] = costs[node] + dist;
                q.push({costs[vecNode], vecNode});
            }
        }
    }

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

    return 0;
}