Cod sursa(job #2683697)

Utilizator marquiswarrenMajor Marquis Warren marquiswarren Data 11 decembrie 2020 23:11:58
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 50001;
const int INF = 1000000000;

int N, M;
int d[NMAX];
vector<pair<int, int>> G[NMAX];
bitset<NMAX> used;

void read() {
    scanf("%d %d\n", &N, &M);
    while (M--) {
        int x, y, c;
        scanf("%d %d %d\n", &x, &y, &c);
        G[x].emplace_back(y, c);
    }
}

void dijkstra() {
    fill(d + 1, d + N + 1, INF);

    priority_queue<pair<int, int>,
            vector<pair<int, int>>,
            greater<>> q;

    q.emplace(0, 1);
    d[1] = 0;

    while (!q.empty()) {
        int x, y, c;

        tie(ignore, x) = q.top();
        q.pop();

        if (used[x]) continue;

        for (auto next: G[x]) {
            tie(y, c) = next;
            if (d[x] + c < d[y]) {
                d[y] = d[x] + c;
                q.emplace(d[y], y);
            }
        }

        used[x] = true;
    }
}

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

    read();
    dijkstra();

    for (int i = 2; i <= N; i++) {
        printf("%d ", d[i] == INF ? 0 : d[i]);
    }

    return 0;
}