Cod sursa(job #2205949)

Utilizator teodoranTeodora Nemtanu teodoran Data 20 mai 2018 17:44:38
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <iostream>
#include <fstream>
#include <list>
#include <vector>
#include <set>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
const int inf = 1000;
int n, m;
vector<list<pair<int, int> > > graph;
///             cost  tag
vector <int> d;
set <pair<int, int> > q;
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 <= n; i++){
        int x, y, c;
        fin >> x >> y >> c;
        graph[x].push_back(make_pair(c, y));
    }
}


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

    while(!q.empty()){
        pair<int, int> node = *q.begin();
        q.erase(q.begin());
        for(auto neighbour : graph[node.second]){
            if(d[node.second] + neighbour.first < d[neighbour.second]){
                d[neighbour.second] = d[node.second] + neighbour.first;
                p[neighbour.second] = node.second;
            }
            q.insert(neighbour);
        }
    }
}

void cost(){
    for(int i = 2; i <= n; i++)
        fout << d[i] << " ";
}

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