Cod sursa(job #1705914)

Utilizator razvan3895Razvan-Mihai Chitu razvan3895 Data 21 mai 2016 07:06:59
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

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


int n;

struct edge {
    int y;
    int c;
};

struct edge_comp {
    bool operator()(const edge &e1, const edge &e2) {
        return e1.c > e2.c;
    }
};

int main() {
    int m;

    in >> n >> m;

    vector<vector<edge> > graph(n + 1);
    vector<int> d(n + 1, INT_MAX);
    vector<bool> sel(n + 1, false);
    priority_queue<edge, vector<edge>, edge_comp> pq;

    for (int i = 0; i < m; ++i) {
        int x, y, c;

        in >> x >> y >> c;

        edge e = {y, c};

        graph[x].push_back(e);
    }

    for (unsigned i = 0; i < graph[1].size(); ++i) {
        d[graph[1][i].y] = graph[1][i].c;

        pq.push(graph[1][i]);
    }

    while (!pq.empty()) {
        edge e = pq.top();

        pq.pop();

        sel[e.y] = true;

        for (unsigned i = 0; i < graph[e.y].size(); ++i) {
            edge n = graph[e.y][i];

            if (d[n.y] > d[e.y] + n.c) {
                d[n.y] = d[e.y] + n.c;
                n.c = d[n.y];
                pq.push(n); 
            }
        }
    }

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

    out << '\n';

    return 0;
}