Cod sursa(job #2173775)

Utilizator savigunFeleaga Dragos-George savigun Data 16 martie 2018 00:44:34
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

struct Node { int x, cost; };

class Cmp {
public:
    bool operator()(Node a, Node b) {
        return a.cost > b.cost;
    }
};

const int INF = 2e9;
const int MAXN = 50005;
int n, m;
int dist[MAXN];
bool viz[MAXN];
vector<Node> g[MAXN];
priority_queue<Node, vector<Node>, Cmp> q;


void Dijkstra() {
    for (int i = 1; i <= n; ++i) dist[i] = INF;
    dist[1] = 0;
    q.push({1, 0});

    while (!q.empty()) {
        Node now = q.top(); q.pop();
        int x = now.x;
        if (viz[x]) continue;
        viz[x] = true;
        dist[x] = now.cost;

        for (Node &e : g[x]) {
            int y = e.x;
            if (viz[y]) continue;
            if (dist[x] + e.cost < dist[y]) {
                dist[y] = dist[x] + e.cost;
                q.push({y, dist[y]});
            }
        }
    }
}

int main()
{
    in >> n >> m;
    for (int i = 1, x, y, cost; i <= m; ++i) {
        in >> x >> y >> cost;
        g[x].push_back({y, cost});
    }

    Dijkstra();

    for (int i = 2; i <= n; ++i)
        if (dist[i] == INF) out << 0 << " ";
            else out << dist[i] << " ";

    return 0;
}