Cod sursa(job #3245201)

Utilizator alexdvResiga Alexandru alexdv Data 27 septembrie 2024 21:28:32
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>

using namespace std;

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

const int NMax = 50005;
const int inf = 0x3f3f3f3f;

int n, m;
int D[NMax];
bool inQueue[NMax];

vector<pair<int, int>> G[NMax];

struct compareDist {
    bool operator() (int x, int y) {
        return D[x] > D[y];
    }
};

priority_queue< int, vector<int>, compareDist> q;

void read() {
    fin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y, cost;
        fin >> x >> y >> cost;
        G[x].push_back(make_pair(y, cost));
    }
}

void Dijkstra(int startNode) {
    for (int i = 1; i <= n; ++i) {
        D[i] = inf;
    }
    D[startNode] = 0;
    q.push(startNode);
    inQueue[startNode] = true;
    while (!q.empty()) {
        int currNode = q.top();
        q.pop();
        inQueue[currNode] = false;
        vector<pair<int, int>> neighbors = G[currNode];
        for (pair<int, int> neighbor: neighbors) {
            if (D[currNode] + neighbor.second < D[neighbor.first]) {
                D[neighbor.first] = D[currNode] + neighbor.second;
                if (!inQueue[neighbor.first]) {
                    q.push(neighbor.first);
                    inQueue[neighbor.first] = true;
                }
            }
        }
    }
}

void print() {
    for (int i = 2; i <= n; ++i) {
        if (D[i] != inf) {
            fout << D[i] << ' ';
        } else {
            fout << "0 ";
        }
    }
}

int main() {
    read();
    Dijkstra(1);
    print();
    return 0;
}