Cod sursa(job #3294039)

Utilizator TeogaloiuMatei Ionescu Teogaloiu Data 15 aprilie 2025 13:09:09
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");

const int INF = 1e9;

struct heapNode {
    int node;
    int val;
    bool operator < (const heapNode& a) const {
        return val > a.val; // pentru min-heap
    }
};

vector<pair<int, int>> v[50001]; // adiacente (vecin, cost)
int ans[50001];
bool visited[50001];

void dijkstra(int start) {
    priority_queue<heapNode> pq;
    pq.push({start, 0});
    ans[start] = 0;

    while (!pq.empty()) {
        heapNode current = pq.top();
        pq.pop();

        int node = current.node;
        int cost = current.val;

        if (visited[node])
            continue;
        visited[node] = true;

        for (auto& neighbour : v[node]) {
            int nextNode = neighbour.first;
            int edgeCost = neighbour.second;

            if (ans[nextNode] > cost + edgeCost) {
                ans[nextNode] = cost + edgeCost;
                pq.push({nextNode, ans[nextNode]});
            }
        }
    }
}

int main() {
    int n, m;
    cin >> n >> m;

    for (int i = 1; i <= n; i++) {
        ans[i] = INF;
        visited[i] = false;
    }

    for (int i = 1; i <= m; i++) {
        int a, b, c;
        cin >> a >> b >> c;
        v[a].emplace_back(b, c);
        v[b].emplace_back(a, c);
    }

    dijkstra(1);

    for (int i = 2; i <= n; i++)
        cout << ans[i] << ' ';
    
    return 0;
}