Cod sursa(job #2596282)

Utilizator segtreapMihnea Andreescu segtreap Data 9 aprilie 2020 15:37:44
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.87 kb
#include <cstdio>
#include <vector>
#include <queue>

using namespace std;

const int N = 50000 + 7;
const int INF = (int) 1e9;

int n;
int m;
vector<pair<int, int>> g[N];
bool vis[N];
int best[N];

struct State {
        int a;
        int d;
};

bool operator < (State a, State b) {
        return a.d > b.d;
}

priority_queue<State> pq;

int main() {
        freopen ("dijkstra.in", "r", stdin);
        freopen ("dijkstra.out", "w", stdout);

        scanf("%d %d", &n, &m);
        for (int i = 1; i <= m; i++) {
                int a, b, c;
                scanf("%d %d %d", &a, &b, &c);
                g[a].push_back({b, c});
        }
        vis[1] = 1;
        for (int i = 2; i <= n; i++) {
                best[i] = INF;
        }
        for (auto &it : g[1]) {
                best[it.first] = min(best[it.first], it.second);
        }
        for (int i = 2; i <= n; i++) {
                pq.push({i, best[i]});
        }
        while (!pq.empty()) {
                State it = pq.top();
                pq.pop();
                if (vis[it.a] == 0) {
                        vis[it.a] = 1;
                        int a = it.a;
                        for (auto &o : g[a]) {
                                int b = o.first;
                                int db = best[a] + o.second;
                                if (db < best[b]) {
                                        best[b] = db;
                                        pq.push({b, db});
                                }
                        }
                }
        }
        for (int i = 2; i <= n; i++) {
                int sol;
                if (best[i] == INF) {
                        sol = 0;
                } else {
                        sol = best[i];
                }
                printf("%d ", sol);
        }
        printf("\n");
}