Cod sursa(job #3296282)

Utilizator radu_pipdmn bro radu_pip Data 12 mai 2025 11:43:28
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <vector>
#include <queue>
#include <limits>
#include <fstream>
using namespace std;
#define INF numeric_limits<int>::max()
struct muchie {
    int to, weight;
};
int n, m, p;
vector<vector<muchie>> g;
vector<int> d;
void dijkstra() {
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    d[1] = 0;
    pq.push(make_pair(0, 1));

    while (!pq.empty()) {
        pair<int, int> curr = pq.top();
        pq.pop();
        int dist = curr.first;
        int x = curr.second;
        if (dist > d[x]) continue;
        for (int i = 0; i < g[x].size(); i++) {
            int v = g[x][i].to, c = g[x][i].weight;
            if (d[x] + c < d[v]) {
                d[v] = d[x] + c;
                pq.push(make_pair(d[v], v));
            }
        }
    }
}
void cit() {
    ifstream fin("dijkstra.in");
    fin >> n >> m ;
    g.resize(n + 1);
    d.assign(n + 1, INF);
    int x, y, z;
    for (int i = 0; i < m; i++) {
        fin >> x >> y >> z;
        g[x].push_back({y, z});
    }
}

void afis() {
    ofstream fout("dijkstra.out");
    for (int i = 2; i <= n; i++) {
        if (d[i] == INF)
            fout << "0 ";
        else
            fout << d[i] << ' ';
    }
    cout << '\n';
}

int main() {
    cit();
    dijkstra();
    afis();
    return 0;
}