Cod sursa(job #1823991)

Utilizator tudormaximTudor Maxim tudormaxim Data 7 decembrie 2016 09:38:03
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

const int nmax = 5e4 + 5;
const int oo = 1 << 29;
vector < pair<int,int> > G[nmax];
int Dist[nmax];

class cmp {
public:
    inline bool operator () (const pair <int,int> &x, const pair <int,int> &y) {
        return x.second > y.second;
    }
};

void Dijkstra(int source, int n) {
    priority_queue <pair <int,int>, vector< pair <int,int> >, cmp> Q;
    vector <pair <int,int> > :: iterator it;
    int node, cost, i;
    for (i = 1; i <= n; i++) {
        Dist[i] = oo;
    }
    Dist[source] = 0;
    Q.push(make_pair(source, Dist[source]));
    while (!Q.empty()) {
        node = Q.top().first;
        cost = Q.top().second;
        Q.pop();
        if (Dist[node] != cost) {
            continue;
        }
        for (it = G[node].begin(); it != G[node].end(); it++) {
            if (Dist[it->first] > Dist[node] + it->second) {
                Dist[it->first] = Dist[node] + it->second;
                Q.push(make_pair(it->first, Dist[it->first]));
            }
        }
    }
}

int main() {
    ios_base :: sync_with_stdio (false);
    int n, m, x, y, i, c;
    fin >> n >> m;
    for (i = 1; i <= m; i++) {
        fin >> x >> y >> c;
        G[x].push_back(make_pair(y, c));
    }
    Dijkstra(1, n);
    for (i = 2; i <= n; i++) {
        if (Dist[i] != oo) {
            fout << Dist[i] << " ";
        } else {
            fout << "0 ";
        }
    }
    fin.close();
    fout.close();
    return 0;
}