Cod sursa(job #1379757)

Utilizator oprea1si2si3Oprea Sebastian oprea1si2si3 Data 6 martie 2015 19:19:05
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

const int kNMax = 50005, Inf = 0x3f3f3f3f;

struct Node {
    int nod, cost;
    Node(int n, int c) {
        nod = n;
        cost = c;
    }
    bool operator<(const Node &other) const {
        return cost > other.cost;
    }
};
int n, dist[kNMax];
vector<pair<int, int>> G[kNMax];
priority_queue<Node> Queue;

void Citire() {
    ifstream in("dijkstra.in");
    int m, x, y, c;
    in >> n >> m;
    for (int i = 1; i <= m; ++i) {
        in >> x >> y >> c;
        G[x].push_back(make_pair(y, c));
    }
    in.close();
}

void Solve() {
    for (int i = 2; i <= n; ++i)
        dist[i] = Inf;
    Queue.push(Node(1, 0));
    while (!Queue.empty()) {
        int nod = Queue.top().nod, cost = Queue.top().cost;
        Queue.pop();
        if (cost > dist[nod])
            continue;
        for (int i = 0; i < G[nod].size(); ++i) {
            int vecin = G[nod][i].first;
            int c = cost + G[nod][i].second;
            if (c < dist[vecin]) {
                dist[vecin] = c;
                Queue.push(Node(vecin, c));
            }
        }
    }
}

void Afisare() {
    ofstream out("dijkstra.out");
    for (int i = 2; i <= n; ++i)
        if (dist[i] == Inf)
            out << "0 ";
        else
            out << dist[i] << ' ';
    out << '\n';
    out.close();
}

int main() {
    Citire();
    Solve();
    Afisare();
    return 0;
}