Cod sursa(job #2424425)

Utilizator mihaicivMihai Vlad mihaiciv Data 22 mai 2019 23:29:11
Problema Algoritmul lui Dijkstra Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define NMAX 100000
#define INF 1e9
using namespace std;

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

int n, m;
priority_queue<pair<int, int > > pq;

int d[NMAX], vis[NMAX];

vector<int> a[NMAX], c[NMAX];

int main() {

    f >> n >> m;
    for (int i = 0; i < m; ++i) {
        int x1, y1, cost1;
        f >> x1 >> y1 >> cost1;
        x1 --;
        y1 --;
        a[x1].push_back(y1);
        c[x1].push_back(cost1);
    }

    for (int i = 0; i < n; ++i) {
        d[i] = INF;
    }

    d[0] = 0;

    pq.push({0, 0});

    for (int i = 0; i < n && !pq.empty(); ++i) {
        pair<int, int> pCurrent = pq.top();
        pq.pop();
        while(!pq.empty() && vis[pCurrent.first] == 1) {
            pCurrent = pq.top();
            pq.pop();
        }

        int nodCurent = pCurrent.second;
        int costCurent = -pCurrent.first;

        vis[nodCurent] = 1;

        for (int j = 0; j < a[nodCurent].size(); ++j) {
            int vecinCurent = a[nodCurent][j];
            if (!vis[vecinCurent] && d[vecinCurent] > c[nodCurent][j] + costCurent) {
                d[vecinCurent] = c[nodCurent][j] + costCurent;
                pq.push(make_pair(-d[vecinCurent], vecinCurent));
            }
        }
    }

    for (int i = 1; i < n; ++i) {
        if (d[i] == INF) {
            g << "0 ";
        } else {
            g << d[i] << " ";
        }
    }


    return 0;
}