Cod sursa(job #1906723)

Utilizator savigunFeleaga Dragos-George savigun Data 6 martie 2017 15:59:55
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 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 destination;
};
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;
    d[1] = 0;
    q.push(1);

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

    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.destination = y;
        e.cost = cost;
        g[x].push_back(e);
    }

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

    in.close();
}