Cod sursa(job #3216869)

Utilizator Robert_OprisanRobert Oprisan Robert_Oprisan Data 20 martie 2024 09:59:45
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
//https://www.infoarena.ro/problema/dijkstra
using namespace std;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");


const int NMAX = 100001;
struct PATH{
    int nod,cost;
};

//nod, cost to nod
vector<PATH>v[NMAX];
int cost[NMAX];
bool masca[NMAX];

struct compara
{
    bool operator()(int x, int y)
    {
        return cost[x] > cost[y];
    }
};
priority_queue<int, vector<int>, compara> q;
int n, m;

void reading(){
    in>> n>> m;
    for (int i = 0; i < m; i++){
        int x, y, c;
        in>> x >> y >> c;
        v[x].push_back({y,c});
    }
    
}

void Dijkstra(int start){
    for (int i = 1; i <=n;i++)
        cost[i]=-1;
    cost[start] = 0;
    q.push(start);
    while(!q.empty()){
        int nod = q.top();
        q.pop();
        for( PATH neigh_path : v[nod]){
            int neigh = neigh_path.nod;
            int c = neigh_path.cost;
            int NewC = cost[nod] + c;
            if(cost[neigh]==-1 || NewC < cost[neigh]){
                cost[neigh] = NewC;
                q.push(neigh);
            }
        }
    }
}

void output(){
    for (int i = 2; i <= n; i++){
        if(cost[i]!=-1)
        out << cost[i] << " ";
        else out << "0 ";
    }
}

int main(){
    reading();
    Dijkstra(1);
    output();
}