Cod sursa(job #3216874)

Utilizator baragan30Baragan Andrei baragan30 Data 20 martie 2024 10:21:28
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 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 isInQueue[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);
    isInQueue[start] = true;
    while(!q.empty()){
        int nod = q.top();
        isInQueue[nod] = false;
        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;
                if(!isInQueue[neigh]){
                   q.push(neigh);
                   isInQueue[neigh] = true;
                }
                
            }
        }
    }
}

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

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