Cod sursa(job #3279137)

Utilizator pascarualexPascaru Alexandru pascarualex Data 21 februarie 2025 22:28:01
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>
using namespace std;

const int MAX_N = 50005;
int dist[MAX_N];
int p[MAX_N];
int vis[MAX_N];

vector<vector<pair<int,int>>> adj(250005);

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

void dijkstra2() {
    int n, m;
    fin >> n >> m;

    for (int i = 0; i <= n; i++) {
        dist[i] = INT_MAX;
        p[i] = -1;
        vis[i] = 0;
    }

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

    priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;
    pq.push({0, 1});
    dist[1] = 0;

    while (!pq.empty()) {
        auto [cost, node] = pq.top();
        pq.pop();

        if (!vis[node]) {
            for (auto [to, w] : adj[node]) {
                if (!vis[to] && cost + w < dist[to]) {
                    dist[to] = cost + w;
                    p[to] = node;
                    pq.push({dist[to], to});
                }
            }
            vis[node] = 1;
        }
    }

    for (int i = 2; i <= n; i++) {
        fout << (dist[i] == INT_MAX ? 0 : dist[i]) << " ";
    }
}

int main() {
    dijkstra2();
    return 0;
}