Cod sursa(job #1906764)

Utilizator savigunFeleaga Dragos-George savigun Data 6 martie 2017 16:17:01
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

struct Edge {
    int cost;
    int node;
};
bool cmp(Edge a, Edge b) { return a.cost > b.cost; }

int n, m, d[50001];
bool viz[50001];
vector<Edge> g[50001];
const int INF = 1e9 * 2 + 1;
priority_queue<Edge, vector<Edge>, decltype(&cmp)> q(cmp);
//priority_queue<int, vector<int>, greater<int> > q;

void citire();


int main()
{
    citire();
    Edge e;
    e.cost = 0;
    e.node = 1;
    q.push(e);

    while (!q.empty()) {
        e = q.top();
        q.pop();
        int x = e.node;
        viz[x] = true;
        for (int i = 0; i < g[x].size(); ++i) {
            int y = g[x][i].node;
            if (!viz[y]) {
                if (e.cost + g[x][i].cost < d[y]) {
                    d[y] = e.cost + g[x][i].cost;
                    Edge edge; edge.cost = d[y]; edge.node = y;
                    q.push(edge);
                }
            }
        }
    }

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

    return 0;
}


void citire() {
    in >> n >> m;
    for (int i = 1, x, y, cost; i <= m; ++i) {
        in >> x >> y >> cost;
        Edge e;
        e.node = y;
        e.cost = cost;
        g[x].push_back(e);
    }

    for (int i = 1; i <= n; ++i)
        d[i] = INF;

    in.close();
}