Cod sursa(job #2556684)

Utilizator nTropicManescu Bogdan Constantin nTropic Data 25 februarie 2020 09:30:34
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <bits/stdc++.h>

using namespace std;

const int len = 250005;
const int inf = 1 << 30;
int m, n, x, y, c, dist[len];
bitset<len> in_queue;
vector<pair<int, int> > g[len];

struct cmp {
    bool operator()(int x, int y) {
        return dist[x] > dist[y];
    }
};

priority_queue<int, vector<int>, cmp> q;

void dijkstra(int start) {
    for (int i = 0; i < n; i++)
        dist[i] = inf;
    dist[start] = 0;
    q.push(start);
    in_queue[start] = true;

    while (!q.empty()) {
        int curr = q.top();
        q.pop();
        in_queue[curr] = false;

        for (auto it : g[curr]) {
            int next = it.first;
            int cost = it.second;

            if (dist[next] > dist[curr] + cost) {
                dist[next] = dist[curr] + cost;

                if (!in_queue[next]) {
                    q.push(next);
                    in_queue[next] = true;
                }
            }
        }
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

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

    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        cin >> x >> y >> c;
        g[x].push_back({y, c});
    }

    dijkstra(1);

    for (int i = 2; i <= n; i++)
        if (dist[i] != inf)
            cout << dist[i] << " ";
        else
            cout << "0 ";
}