Cod sursa(job #3342392)

Utilizator uncle_sam_007ioan bulik uncle_sam_007 Data 23 februarie 2026 23:29:48
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int NMAX = 50005;
const int INF = 1e9;

struct Muchie{
    int to, cost;
};

vector <Muchie> g[NMAX];

int dist[NMAX];
int pred[NMAX];

#define pii pair <int, int>
priority_queue <pii, vector <pii>, greater <pii>> pq;

void dijkstra(int start){
    dist[start] = 0;
    pq.push({0, start});
    while(!pq.empty()){
        pii temp = pq.top();
        pq.pop();
        if(dist[temp.second] != temp.first){
            continue;
        }
        for(auto edge:g[temp.second]){
            if(dist[edge.to] > dist[temp.second] + edge.cost){
                dist[edge.to] = dist[temp.second] + edge.cost;
                pred[edge.to] = temp.second;
                pq.push({dist[edge.to], edge.to});
            }
        }
    }
}

void solve(){
    int n, m;
    fin >> n >> m;
    for(int i = 1; i <= m; ++i){
        int x, y, cost;
        fin >> x >> y >> cost;
        Muchie temp;
        temp.to = y;
        temp.cost = cost;
        g[x].push_back(temp);
    }
    for(int i = 1; i <= n; ++i){
        dist[i] = INF;
        pred[i] = -1;
    }
    dijkstra(1);
    for(int i = 2; i <= n; ++i){
        if(dist[i] == INF){
            fout << -1 << " ";
        }
        else
            fout << dist[i] << " ";
    }
}

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