Cod sursa(job #3167465)

Utilizator R4phaCrisan Andrei R4pha Data 10 noiembrie 2023 18:55:12
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

const int MAX_N = 50000;
const int MAX_M = 250000;

struct Arc {
    int destinatie, lungime;
};

vector<Arc> graf[MAX_N + 1];

void dijkstra(int N) {
    vector<int> dist(N + 1, INT_MAX);
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;

    for(int i=1;i<=N;i++)
        dist[i]=MAX_M;

    dist[1] = 0;
    pq.push({0, 1});

    while (!pq.empty()) {
        int u = pq.top().second;
        int cost = pq.top().first;
        pq.pop();

        if (cost > dist[u]) continue;

        for (Arc& arc : graf[u]) {
            int v = arc.destinatie;
            int weight = arc.lungime;

            if (dist[u] + weight < dist[v]) {
                dist[v] = dist[u] + weight;
                pq.push({dist[v], v});
            }
        }
    }

    ofstream fout("dijkstra.out");
    for (int i = 2; i <= N; i++) {
        fout << dist[i] << " ";
    }
    fout.close();
}

int main() {
    ifstream fin("dijkstra.in");
    int N, M;
    fin >> N >> M;

    for (int i = 0; i < M; i++) {
        int A, B, C;
        fin >> A >> B >> C;
        graf[A].push_back({B, C});
    }
    fin.close();

    dijkstra(N);

    return 0;
}