Cod sursa(job #1920207)

Utilizator mariapascuMaria Pascu mariapascu Data 9 martie 2017 22:58:30
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

struct Pair{
    int x, w;
    bool operator < (const Pair & A) const {
        return w > A.w;
    }
};

const int INF = 0x3f3f3f3f;
int n, m;
vector<vector<pair<int,int>>> G;
vector<int> D;
priority_queue<Pair> Q;

void Read();
void Dijkstra();
void Write();

int main() {
    Read();
    Dijkstra();
    Write();

    fin.close();
    fout.close();
    return 0;
}

void Dijkstra() {
    D[1] = 0;
    Q.push({1, 0});
    int x, dx, y, w;
    while (!Q.empty()) {
        x = Q.top().x;
        dx = Q.top().w;
        Q.pop();
        if (dx > D[x]) continue;
        for (const auto & e : G[x]) {
            y = e.first; w = e.second;
            if (D[y] > dx + w) {
                D[y] = dx + w;
                Q.push({y, D[y]});
            }
        }
    }
}

void Write() {
    for (int i = 2; i <= n; i++)
        if (D[i] == INF) fout << "0 ";
        else fout << D[i] << ' ';
}

void Read() {
    fin >> n >> m;
    G = vector<vector<pair<int, int>>>(n + 1);
    D = vector<int>(n + 1, INF);
    int x, y, w;
    for (int i = 1; i <= m; i++) {
        fin >> x >> y >> w;
        G[x].push_back({y, w});
    }
}