Cod sursa(job #3342985)

Utilizator Barbu_MateiBarbu Matei Barbu_Matei Data 26 februarie 2026 12:01:56
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <bits/stdc++.h>
using namespace std;

struct nodeType {
    int node, cost;
};

struct comp {
    bool operator()(nodeType a, nodeType b) {
        return a.cost > b.cost;
    }
};

int n, m, cost[50001];
vector<nodeType> v[50001];
priority_queue<nodeType, vector<nodeType>, comp> q;

void dijkstra(int start) {
    memset(cost, 0x3f, sizeof(cost));
    q.push({1, 0});
    cost[1] = 0;
    while (!q.empty()) {
        int node = q.top().node;
        int pastCost = q.top().cost;
        q.pop();
        if (pastCost == cost[node]) {
            for (int i = 0; i < v[node].size(); ++i) {
                if (cost[node] + v[node][i].cost < cost[v[node][i].node]) {
                    cost[v[node][i].node] = cost[node] + v[node][i].cost;
                    q.push({v[node][i].node, cost[v[node][i].node]});
                }
            }
        }
    }
}

int main() {
    ifstream cin("dijkstra.in");
    ofstream cout("dijkstra.out");
    cin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int x, y, c;
        cin >> x >> y >> c;
        v[x].push_back({y, c});
    }
    dijkstra(1);
    for (int i = 2; i <= n; ++i) {
        if (cost[i] == 0x3f3f3f3f) {
            cost[i] = 0;
        }
        cout << cost[i] << " ";
    }
}