Cod sursa(job #2760614)

Utilizator tryharderulbrebenel mihnea stefan tryharderul Data 28 iunie 2021 10:31:36
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 50003;
const int ELEMENT_NEUTRU =  INT_MAX;

int n, m;

struct muchie {
    int y, c;
};

vector<muchie> g[NMAX];
int dist[NMAX];

class Cmp {
public:
    bool operator()(int x, int y) {
        return dist[x] > dist[y];
    }
};

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

void Djikstra() {
    for (int i = 1; i <= n; i++)
        dist[i] = ELEMENT_NEUTRU;
    dist[1] = 0;
    q.push(1);
    while (!q.empty()) {
        int nod = q.top();
        q.pop();
        for (muchie edge:g[nod]) {
            if (dist[nod] + edge.c < dist[edge.y]) {
                dist[edge.y] = dist[nod] + edge.c;
                q.push(edge.y);
            }
        }
    }
    for (int i = 1; i <= n; i++)
        if (dist[i] == ELEMENT_NEUTRU)
            dist[i] = 0;

}

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 x, y, cost;
        scanf("%d %d %d", &x, &y, &cost);
        g[x].push_back({y, cost});
    }
    Djikstra();
    for (int i = 2; i <= n; i++)
        printf("%d ", dist[i]);
    return 0;
}