Cod sursa(job #2761287)

Utilizator tryharderulbrebenel mihnea stefan tryharderul Data 1 iulie 2021 14:50:23
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 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];
bool seen[NMAX];

priority_queue<pair<int,int>> q;

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

}

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++) {
        if (dist[i] == ELEMENT_NEUTRU)printf("0 ");
        else printf("%d ", dist[i]);
    }
    return 0;
}