Cod sursa(job #2907257)

Utilizator Apyxabcdefghij Apyx Data 29 mai 2022 14:28:02
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <bits/stdc++.h>
#define nmax 50000

using namespace std;

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

vector<pair<int,int>> v[nmax+5];
priority_queue<pair<int,int>> pq;
int cost[nmax+5];

int main() {
    int n, m; fin >> n >> m;
    for(int i = 1; i <= m; i++) {
        int x, y, c; fin >> x >> y >> c;
        v[x].emplace_back(c, y);
    }
    for(int i = 1; i <= n; i++) {
        cost[i] = INT_MAX;
    }
    cost[1] = 0;
    pq.push({0, 1});
    while(!pq.empty()) {
        pair<int,int> now = pq.top();
        pq.pop();
        if(cost[now.second] < -now.first) {
            continue;
        }
        for(auto x : v[now.second]) {
            if(-now.first + x.first < cost[x.second]) {
                cost[x.second] = -now.first + x.first;
                pq.push({-(-now.first + x.first), x.second});
            }
        }
    }
    for(int i = 2; i <= n; i++) {
        if(cost[i] == INT_MAX) {
            fout << 0 << " ";
        } else {
            fout << cost[i] << " ";
        }
    }
    return 0;
}