Cod sursa(job #3284415)

Utilizator LuciBBadea Lucian LuciB Data 11 martie 2025 16:49:57
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>
using namespace std;

const int NMAX = 5e4;
const int MMAX = 25e4;
const int INF = 2e9;

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


struct edge {
    int to, cost;
};

struct cell {
    int node;
    int dist;
};

struct cmp {
    bool operator()(const cell a, const cell b) const {
        return a.dist > b.dist;
    }
};

vector<edge> graph[NMAX];
int n;

int mindist[NMAX];
bool vis[NMAX];

priority_queue<cell, vector<cell>, cmp> pq;

void dijkstra(int node) {
    for(int i = 0; i < n; i++)
        mindist[i] = INF;
    mindist[node] = 0;
    pq.push({0, node});
    while(!pq.empty()) {
        cell c = pq.top();
        pq.pop();
        if(!vis[c.node]) {
            vis[c.node] = true;
            for(auto x : graph[c.node]) {
                if(c.dist + x.cost < mindist[x.to]) {
                    mindist[x.to] = c.dist + x.cost;
                    pq.push({x.to, mindist[x.to]});
                }
            }
        }
    }
}

int main() {
    int m;
    fin >> n >> m;
    for(int i = 0; i < m; i++) {
        int a, b, c;
        fin >> a >> b >> c;
        a--, b--;
        graph[a].push_back({b, c});
    }

    dijkstra(0);
    for(int i = 1; i < n; i++)
        fout << (mindist[i] == INF ? 0 : mindist[i]) << ' ';
    return 0;
}