Cod sursa(job #2944796)

Utilizator radubuzas08Buzas Radu radubuzas08 Data 22 noiembrie 2022 22:48:00
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
//
// Created by Radu Buzas on 22.11.2022.
//
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

struct cost{
    int c, x;
    bool operator<(const cost & o) const{
        return (this->c > o.c);
    }
};

int n, m;
vector<vector<cost>> graph;
int d[50001];

void dijkstra(int x){
    d[x] = 0;
    priority_queue<cost> q;
    struct cost S;
    S.c = 0; S.x = x;
    q.push(S);
    while (!q.empty()){
        int cost = q.top().c;
        int nod = q.top().x;
        q.pop();
        int size = graph[nod].size();
        for (int i = 0; i < size; ++i) {
            if(cost + graph[nod][i].c < d[graph[nod][i].x]){
                d[graph[nod][i].x] = cost + graph[nod][i].c;
                S.c = cost + graph[nod][i].c;
                S.x = graph[nod][i].x;
                q.push(S);
            }
        }
    }
}

int main(){
    in >> n >> m;
    const int inf = ((unsigned)1 << 31) -1;
    graph.resize(n+1);
    for(int i = 1; i <=n; ++i)
        d[i] = inf;
    for(int i = 1; i <= m; ++i){
        int x;
        struct cost S;
        in >> x >> S.x >> S.c;
        graph[x].push_back(S);
//        graph[y].push_back({x, c});
    }
    dijkstra(1);
    for (int i = 2; i <= n; ++i) {
        if(d[i] == ((unsigned)1 << 31) -1)
            out << 0 << ' ';
        else
            out << d[i] << ' ';
    }
    in.close();
    out.close();
    return 0;
}