Cod sursa(job #2238015)

Utilizator sorynsooSorin Soo sorynsoo Data 4 septembrie 2018 11:31:27
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

#define MAXN 50000
#define INF 0x3f3f3f3f

struct Node {
    int node;
    int cost;
};

class Comp {
public:
    bool operator()(Node A, Node B) {
        return A.cost > B.cost;
    }
};

vector<Node> graf[MAXN];
priority_queue<Node, vector<Node>, Comp> pq;
int costUntil[MAXN];

int main() {
    int n, m;
    fin >> n >> m;

    for(int i = 1; i <= m; i++) {
        Node crtNode;
        int x;
        fin >> x >> crtNode.node >> crtNode.cost;

        graf[x].push_back(crtNode);
    }

    for(int i = 1; i <= n; i++) {
        costUntil[i] = INF;
    }

    Node startingNode;
    startingNode.node = 1;
    startingNode.cost = 0;
    costUntil[1] = 0;

    pq.push(startingNode);

    while(!pq.empty()) {
        Node crtNode = pq.top(); pq.pop();

        // Check if cost hasn't already changed
        if(crtNode.cost != costUntil[crtNode.node])
            continue;

        for(int i = 0; i < graf[crtNode.node].size(); i++) {
            Node nextNode = graf[crtNode.node][i];

            if( costUntil[nextNode.node] > costUntil[crtNode.node] + nextNode.cost ) {
                costUntil[nextNode.node] = costUntil[crtNode.node] + nextNode.cost;
                nextNode.cost = costUntil[nextNode.node];
                pq.push(nextNode);
            }
        }
    }

    for(int i = 2; i <= n; i++) {
        fout << costUntil[i] << " ";
    }

    return 0;
}