Cod sursa(job #2308147)

Utilizator ioana_marinescuMarinescu Ioana ioana_marinescu Data 26 decembrie 2018 14:47:26
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <fstream>
#include <queue>

const int MAX_N = 50000;
const int INF = 0x7ffffff;

using namespace std;

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

int n, m;
int dist[MAX_N + 5];

struct Node {
    int v, cost;
    bool operator < (const Node other) const{
        return this->cost > other.cost;
    }
};

vector<Node> neighbors[MAX_N + 5];
priority_queue<Node> pq;

void dijkstra() {
    for(int u = 1; u <= n; u++)
        dist[u] = INF;
    dist[1] = 0;

    pq.push({1, 0});

    while(!pq.empty()) {
        Node u = pq.top();
        pq.pop();

        for(auto v : neighbors[u.v])
            if(dist[v.v] > dist[u.v] + v.cost) {
                dist[v.v] = dist[u.v] + v.cost;
                pq.push({v.v, dist[v.v]});
            }
    }
}
int main()
{
    fin >> n >> m;
    while(m--) {
        int a, b, c;
        fin >> a >> b >> c;
        neighbors[a].push_back({b, c});
    }

    dijkstra();

    for(int i = 2; i <= n; i++) {
        if(dist[i] == INF)
            dist[i] = 0;
        fout << dist[i] << " ";
    }
    return 0;
}