Cod sursa(job #2944810)

Utilizator radubuzas08Buzas Radu radubuzas08 Data 22 noiembrie 2022 23:18:40
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
//
// Created by Radu Buzas on 22.11.2022.
//
#include <fstream>
#include <vector>
#include <queue>
#define inf 200000005
using namespace std;

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

int n, m, x, y, c;
vector<vector<pair<int, int>>> graph;
int d[50001];

void dijkstra(int x){
    for(int i = 1; i <=n; ++i)
        d[i] = inf;
    d[x] = 0;
    priority_queue<pair<int, int>> q;
    q.push(make_pair(0,x));
    while (!q.empty()){
        int cost = -q.top().first;
        int nod = q.top().second;
        q.pop();
        int size = graph[nod].size();
        for (int i = 0; i < size; ++i) {
            int C = graph[nod][i].first;
            int N = graph[nod][i].second;
            if(cost + C < d[N]){
                d[N] = cost + C;
                q.push(make_pair(- cost - C, N));
            }
        }
    }
}

int main(){
    fin >> n >> m;
    graph.resize(n+1);
    for(int i = 1; i <= m; ++i){
        fin >> x >> y >> c;
        graph[x].push_back({c, y});
//        graph[y].push_back({x, c});
    }
    dijkstra(1);
    for (int i = 2; i <= n; ++i) {
        if(d[i] == inf)
            fout << 0 << ' ';
        else
            fout << d[i] << ' ';
    }
    return 0;
}