Cod sursa(job #3216876)

Utilizator Robert_OprisanRobert Oprisan Robert_Oprisan Data 20 martie 2024 10:23:12
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 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();
        q.pop();
        IsInQueue[nod]=false;
        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 << cost[i] << " ";
        else out << "0 ";
    }
}

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