Cod sursa(job #2076890)

Utilizator sebi_andrei2008Lazar Eusebiu sebi_andrei2008 Data 27 noiembrie 2017 12:53:58
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <utility>
#include <set>
#define INFINITY 2147483647
#define MAX_N 50001
using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
vector<pair<int, int>> graf[MAX_N];
int dist[MAX_N];
int n, m;
int source;
multiset<pair<int, int>> q;

int main() {
    fin>>n>>m;
    source = 1;
    
    for (int i = 0; i < m; i++) {
        int a, b, c;
        fin>>a>>b>>c;
        graf[a].push_back(make_pair(b, c));
    }
    
    for (int i = 1; i <= n; i++) {
        dist[i] = INFINITY;
        if (i == source)
            dist[i] = 0;
        q.insert(make_pair(i, dist[i]));
    }
    
    while (!q.empty()) {
        pair<int, int> nod = *q.begin();
        q.erase(q.begin());
        
        vector<pair<int, int>> neighbours = graf[nod.first];
        vector<pair<int, int>>::iterator it;
        for (it = neighbours.begin(); it != neighbours.end(); it++) {
            pair<int, int> neighbour = *it;
            if (q.find(make_pair(neighbour.first, dist[neighbour.first])) != q.end()) {
                int alt = dist[nod.first] + neighbour.second;
                if (alt < dist[neighbour.first]) {
                    q.erase(make_pair(neighbour.first, dist[neighbour.first]));
                    dist[neighbour.first] = alt;
                    q.insert(make_pair(neighbour.first, dist[neighbour.first]));
                }
            }
        }
    }
    
    for (int i = 1; i <= n; i++) {
        if (i != source) {
            if (dist[i] == INFINITY)
                fout<<"0 ";
            else
                fout<<dist[i]<<" ";
        }
    }
    return 0;
}