Cod sursa(job #1923104)

Utilizator alinp25Alin Pisica alinp25 Data 10 martie 2017 20:45:27
Problema Algoritmul lui Dijkstra Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>
#include <vector>
#include <queue>
#include <iostream>


#define inf 0x3f3f3f3f


typedef std::pair < int, int > iPair;
int n;
std::vector < int > d(50001, inf);
std::vector < iPair > v[50001];
int node, next, cost;
std::priority_queue < iPair, std::vector < iPair >, std::greater < iPair > > pq;


void read() {
    std::ifstream fin("dijkstra.in");
    int x, y, w, m;
    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        fin >> x >> y >> w;
        v[x].push_back(std::make_pair(y, w));
    }
    fin.close();
}


void printSol() {
    std::ofstream fout("dijkstra.out");
    for (int i = 2; i <= n; i++) {
        if (d[i] == inf) {
            fout << "0 ";
        } else {
            fout << d[i] << " ";
        }
    }
    fout.close();
}


void solve() {
    d[1] = 0;
    pq.push(std::make_pair(1, 0));
    while (!pq.empty()) {
        node = pq.top().first;
        pq.pop();
        for (int i = 0; i < v[node].size(); i++) {
            next = v[node][i].first;
            cost = v[node][i].second;
            if (d[next] > d[node] + cost) {
                d[next] = d[node] + cost;
                pq.push(std::make_pair(next, d[next]));
            }
        }
    }
}


int main(int argc, char *argv[]) {
    read();
    solve();
    printSol();
    return 0;
}