Cod sursa(job #2205981)

Utilizator teodoranTeodora Nemtanu teodoran Data 20 mai 2018 19:41:55
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 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;
///     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 <= n; i++){
        int x, y, c;
        fin >> x >> y >> c;
        graph[x].push_back(make_pair(c, y));
    }
}


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++)
        fout << d[i] << " ";
  //  for(int i = 1; i <= n; i++)
  //      cout << p[i] << " ";
}

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