Cod sursa(job #2205990)

Utilizator teodoranTeodora Nemtanu teodoran Data 20 mai 2018 20:07:29
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <iostream>
#include <fstream>
#include <list>
#include <vector>
#include <set>

#define inf 0x3f3f3f3f
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

int n, m;
vector<list<pair<int, int> > > graph;
///             cost  tag
vector<int> d;
set<pair<int, int> > q;
///     d[tag] tag
vector<int> p;


void read() {
    fin >> n >> m;
    graph.resize(n + 1);
    d.resize(n + 1);
    p.resize(n + 1);

    for (int i = 1; i <= m; i++) {
        int x, y, c;
        fin >> x >> y >> c;
        graph[x].push_back(make_pair(c, y));
    }
    /*
    for(int i = 1; i <= n; i++){
        cout << i << " : ";
        for(auto x : graph[i]){
            cout << "( " << x.first << " " << x.second <<"), ";
        }
        cout << "\n";
    }*/
}


void Dijkstra() {
    for (int i = 1; i <= n; i++) {
        d[i] = inf;
        p[i] = -1;
    }
    d[1] = p[1] = 0;
    q.insert(make_pair(d[1], 1));

    while (!q.empty()) {
        pair<int, int> node = *q.begin();
        int u = node.second;
        q.erase(q.begin());

        for (auto neighbour : graph[u]) {
            int v = neighbour.second;
            int weight = neighbour.first;

            if (d[u] + weight < d[v]) {
                if (d[v] != inf)
                    q.erase(q.find(make_pair(d[v], v)));

                d[v] = d[u] + weight;
                p[v] = u;
                q.insert(make_pair(d[v], v));
            }
        }
    }
}

void cost() {
    for (int i = 2; i <= n; i++)
        if (d[i] != inf) {
            fout << d[i] << " ";
        } else fout << "0" << " ";
    //  for(int i = 1; i <= n; i++)
    //      cout << p[i] << " ";
}

int main() {
    read();
    Dijkstra();
    cost();
    return 0;
}