Cod sursa(job #2819390)

Utilizator Ionut151Marcu Ionut Ionut151 Data 18 decembrie 2021 12:00:23
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <iostream>
#include <algorithm>
#include <functional>
#include <queue>
#include <vector>
#include <fstream>
#include <cstring>

using namespace std;

#define PAIR pair<int,int>

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

const int inf = 1e9;
int n,m;
int d[50001];
vector<vector<PAIR> > g(50001);
priority_queue<PAIR, vector<PAIR>,greater<PAIR>> pq;

void djk(){
    for(int i=1;i<=n;i++)
        d[i] = inf;
    d[1] = 0;
    pq.push({0,1});
    while(!pq.empty()){
        PAIR p = pq.top();
        int dist,nod;
        dist = p.first;
        nod = p.second;
        pq.pop();
        if(dist > d[nod])
            continue;

        for(auto next: g[nod]){
            if(d[next.first] > dist + next.second){
                d[next.first] = dist + next.second;
                pq.push({d[next.first],next.first});
            }
        }
    }
}

int main()
{
    in >> n >> m;
    for(int i=1;i<=m;i++){
        int a,b,c;
        in >> a >> b >> c;
        g[a].push_back(make_pair(b,c));
    }
    djk();
    for(int i=2;i<=n;i++){
        if(d[i] == inf)
            out << 0;
        else
            out << d[i];
        out <<" ";
    }
    return 0;
}